diff --git a/.github/workflows/sumocli-build.yml b/.github/workflows/sumocli-build.yml index 001fbd30..c455825f 100644 --- a/.github/workflows/sumocli-build.yml +++ b/.github/workflows/sumocli-build.yml @@ -34,7 +34,7 @@ jobs: - name: Setup Go uses: actions/setup-go@v2 with: - go-version: '1.16.6' + go-version: '1.17' - name: Setup Dotnet uses: actions/setup-dotnet@v1 with: @@ -64,7 +64,7 @@ jobs: - name: Signing Executable shell: pwsh run: | - azuresigntool sign --description-url "https://sumocli.gitbook.io" --file-digest sha256 ` + azuresigntool sign --description-url "https://github.com/wizedkyle/sumocli" --file-digest sha256 ` --azure-key-vault-url ${{ secrets.AZURE_KEY_VAULT_URL }} ` --azure-key-vault-client-id ${{ secrets.AZURE_KEY_VAULT_CLIENT_ID }} ` --azure-key-vault-client-secret ${{ secrets.AZURE_KEY_VAULT_CLIENT_SECRET }} ` @@ -85,6 +85,11 @@ jobs: asset_path: ./sumocli-windows-amd64.zip asset_name: sumocli-windows-amd64.zip asset_content_type: application/zip + - name: Upload Artifact + uses: actions/upload-artifact@v2 + with: + name: sumocli-windows-amd64 + path: ./sumocli.exe build_linux: name: Build Linux Binary @@ -94,7 +99,7 @@ jobs: - name: Setup Go uses: actions/setup-go@v2 with: - go-version: '1.16.6' + go-version: '1.17' - name: Set Version Variable run: | echo "TAG=${GITHUB_REF/refs\/tags\/}" >> $GITHUB_ENV @@ -126,6 +131,11 @@ jobs: asset_path: ./sumocli-linux-amd64.zip asset_name: sumocli-linux-amd64.zip asset_content_type: application/zip + - name: Upload Artifact + uses: actions/upload-artifact@v2 + with: + name: sumocli-linux-amd64 + path: ./sumocli build_macos_intel: name: Build macOS Binary (Intel) @@ -135,7 +145,7 @@ jobs: - name: Setup Go uses: actions/setup-go@v2 with: - go-version: '1.16.6' + go-version: '1.17' - name: Set Version Variable run: | echo "TAG=${GITHUB_REF/refs\/tags\/}" >> $GITHUB_ENV @@ -196,6 +206,12 @@ jobs: asset_path: ./sumocli.zip asset_name: sumocli-macos-amd64.zip asset_content_type: application/zip + - name: Upload Artifact + uses: actions/upload-artifact@v2 + with: + name: sumocli-macos-amd64 + path: ./sumocli + build_macos_apple_silicon: name: Build macOS Binary (Apple Silicon) @@ -205,7 +221,7 @@ jobs: - name: Setup Go uses: actions/setup-go@v2 with: - go-version: '1.16.6' + go-version: '1.17' - name: Set Version Variable run: | echo "TAG=${GITHUB_REF/refs\/tags\/}" >> $GITHUB_ENV @@ -262,3 +278,8 @@ jobs: asset_path: ./sumocli.zip asset_name: sumocli-macos-arm64.zip asset_content_type: application/zip + - name: Upload Artifact + uses: actions/upload-artifact@v2 + with: + name: sumocli-macos-arm64 + path: ./sumocli diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md index e441c801..c2055ae9 100644 --- a/COMPATIBILITY.md +++ b/COMPATIBILITY.md @@ -12,6 +12,7 @@ You can find further information about the Sumo Logic APIs in their [documentati | Account | :white_check_mark: | | | Apps (Beta) | :white_check_mark: | | | Archive Ingestion | :white_check_mark: | | +| Connections (Beta) | | Functionality is still in development. | | Content | :white_check_mark: | | | Collectors | :white_check_mark: | | | Dashboards | :white_check_mark: | | @@ -22,17 +23,22 @@ You can find further information about the Sumo Logic APIs in their [documentati | Health Events | :white_check_mark: | | | Ingest Budgets | :white_check_mark: | | | Ingest Budgets v2 | :white_check_mark: | | -| Lookup Tables | :white_check_mark: | Upload CSV file functionality is not currently supported however, it will be added in a future release. | +| Log Search Estimated Usage | | Functionality is still in development. | +| Lookup Tables | :white_check_mark: | | +| Metrics Searches (Beta) | | Functionality is still in development. | | Monitors | | Functionality is still in development. | +| Organizations | | Functionality is still in development. | | Partitions | :white_check_mark: | | | Password Policy | :white_check_mark: | | | Permissions | :white_check_mark: | | +| Policies | | Functionality is still in development. | | Roles | :white_check_mark: | | | SAML Configuration | :white_check_mark: | | | Scheduled Views | :white_check_mark: | | | Service Allowlist | :white_check_mark: | | | Sources | :white_check_mark: | Simple commands like get, list, delete are supported. Support for creating different sources are listed under Sumo Logic Sources Support. | | Tokens | :white_check_mark: | | +| Transformation Rules (Beta) | | Functionality is still in development. | | Users | :white_check_mark: | | ## Sumo Logic Sources Support diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..d7f71d2b --- /dev/null +++ b/Dockerfile @@ -0,0 +1,11 @@ +FROM golang:1.16.6-alpine +LABEL maintainer="Kyle Jackson " + +ENV DEV=true + +WORKDIR $GOPATH/src/github.com/wizedkyle/sumocli +COPY . . +RUN chmod +x ./scripts/build.sh +RUN ./scripts/build.sh + +ENTRYPOINT ["/go/bin/sumocli"] diff --git a/LICENSE b/LICENSE index f288702d..261eeb9e 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,201 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 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 General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is 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. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - 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. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - 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 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. Use with the GNU Affero General Public License. - - 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 Affero 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 special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU 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 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 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 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 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - 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 GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index d1c90cd8..737ba0fe 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,18 @@ GA will be v1.0.0 which I am expecting to be ready for release towards the end o ### Recommended Download the binary for your platform from the Releases page. +### Docker + +Each version of Sumocli is published on [Docker Hub](https://hub.docker.com/r/wizedkyle/sumocli). + +Pull the latest image: + +`docker pull wizedkyle/sumocli:latest` + +Pull a specific version image: + +`docker pull wizedkyle/sumocli:v0.11.0` + ### Build Yourself You can build the sumocli application for your platform by performing the following steps: diff --git a/api/collectors.go b/api/collectors.go deleted file mode 100644 index 3707f061..00000000 --- a/api/collectors.go +++ /dev/null @@ -1,87 +0,0 @@ -package api - -type Collectors struct { - Data []CollectorsResponse `json:"collectors"` -} - -type CreateCollectorRequest struct { - Collector CreateCollector `json:"collector"` -} - -type CreateCollector struct { - CollectorType string `json:"collectorType"` - Name string `json:"name"` - Description string `json:"description,omitempty"` - Category string `json:"category,omitempty"` - Fields map[string]string `json:"fields,omitempty"` -} - -type CollectorResponse struct { - Collector CollectorsResponse `json:"collector"` -} - -type CollectorsResponse struct { - Alive bool `json:"alive"` - Category string `json:"category,omitempty"` - CollectorType string `json:"collectorType"` - CollectorVersion string `json:"collectorVersion"` - CutoffRelativeTime string `json:"cutoffRelativeTime,omitempty"` - CutoffTimestamp int `json:"cutoffTimestamp,omitempty"` - Description string `json:"description,omitempty"` - Ephemeral bool `json:"ephemeral"` - Fields map[string]string `json:"fields,omitempty"` - Links []collectorLinks `json:"links,omitempty"` - HostName string `json:"hostName,omitempty"` - Id int `json:"id"` - LastSeenAlive int `json:"lastSeenAlive,omitempty"` - Name string `json:"name"` - SourceSyncMode string `json:"sourceSyncMode,omitempty"` - TimeZone string `json:"timeZone,omitempty"` - TargetCpu int `json:"targetCpu,omitempty"` - OsName string `json:"osName,omitempty"` - OsVersion string `json:"osVersion,omitempty"` - OsArch string `json:"osArch,omitempty"` - OsTime int `json:"osTime,omitempty"` -} - -type Targets struct { - Targets []targetsResponse `json:"targets"` -} - -type UpgradeTask struct { - CollectorId int `json:"collectorId"` - ToVersion string `json:"toVersion"` -} - -type UpgradeTaskResponse struct { - Id string `json:"id"` - Link upgradeTaskLink `json:"link"` -} - -type UpgradeTaskStatus struct { - Upgrade upgradeTaskProgress `json:"upgrade"` -} - -type collectorLinks struct { - Rel string `json:"rel"` - Href string `json:"href"` -} - -type targetsResponse struct { - Version string `json:"version"` - Latest bool `json:"latest"` -} - -type upgradeTaskLink struct { - Rel string `json:"rel"` - Href string `json:"href"` -} - -type upgradeTaskProgress struct { - Id int `json:"id"` - CollectorId int `json:"collectorId"` - ToVersion string `json:"toVersion"` - RequestTime int `json:"requestTime"` - Status int `json:"status"` - Message string `json:"message"` -} diff --git a/api/content.go b/api/content.go deleted file mode 100644 index 15851d8e..00000000 --- a/api/content.go +++ /dev/null @@ -1,304 +0,0 @@ -package api - -type DashboardSyncDefinition struct { - Type string `json:"type"` - Name string `json:"name"` - Description string `json:"description"` - DetailLevel int `json:"detailLevel"` - Properties string `json:"properties"` - Panels []reportPanelSyncDefinition `json:"panels"` - Filters []filtersSyncDefinition `json:"filters"` -} - -type FolderSyncDefinition struct { - Type string `json:"type"` - Name string `json:"name"` - Description string `json:"description"` - Children []contentSyncDefinition `json:"children"` -} - -type GetContentResponse struct { - CreatedAt string `json:"createdAt"` - CreatedBy string `json:"createdBy"` - ModifiedAt string `json:"modifiedAt"` - ModifiedBy string `json:"modifiedBy"` - Id string `json:"id"` - Name string `json:"name"` - ItemType string `json:"itemType"` - ParentId string `json:"parentId"` - Permissions []string `json:"permissions"` -} - -type GetPathResponse struct { - Path string `json:"path"` -} - -type LookupTableSyncDefinition struct { - Type string `json:"type"` - Name string `json:"name"` - Description string `json:"description"` - Fields []fields `json:"fields"` - PrimaryKeys []string `json:"primaryKeys"` - TTL int `json:"ttl"` - SizeLimitAction string `json:"sizeLimitAction"` -} - -type MetricsSavedSearchSyncDefinition struct { - Type string `json:"type"` - Name string `json:"name"` - Description string `json:"description"` - TimeRange timeRangeDefinition `json:"timeRange"` - LogQuery string `json:"logQuery"` - MetricsQueries []metricsQueriesDefinition `json:"metricsQueries"` - DesiredQuantizationInSecs int `json:"desiredQuantizationInSecs"` - Properties string `json:"properties"` -} - -type MetricsSearchSyncDefinition struct { - Type string `json:"type"` - Name string `json:"name"` - TimeRange timeRangeDefinition `json:"timeRange"` - Description string `json:"description"` - Queries []queries `json:"queries"` - VisualSettings string `json:"visualSettings"` -} - -type MewboardSyncDefinition struct { - Type string `json:"type"` - Name string `json:"name"` - Description string `json:"description"` - Title string `json:"title"` - RootPanel rootPanelDefinition `json:"rootPanel"` - Theme string `json:"theme"` - TopologyLabelMap topologyLabelMap `json:"topologyLabelMap"` - RefreshInterval int `json:"refreshInterval"` - TimeRange timeRangeDefinition `json:"timeRange"` - Layout layout `json:"layout"` - Panels panelsDefinition `json:"panels"` - Variables variablesDefinition `json:"variables"` - ColoringRules coloringRulesDefinition `json:"coloringRules"` -} - -type MoveResponse struct { - Id string `json:"id"` - Errors []moveErrors `json:"errors"` -} - -type ResponseType struct { - Type string `json:"type"` -} - -type SavedSearchWithScheduleSyncDefinition struct { - Type string `json:"type"` - Name string `json:"name"` - Search search `json:"search"` - SearchSchedule searchSchedule `json:"searchSchedule"` - Description string `json:"description"` -} - -type StartExportResponse struct { - Id string `json:"id"` -} - -type ExportStatusResponse struct { - Status string `json:"status"` - StatusMessage string `json:"statusMessage,omitempty"` - Error exportError `json:"error,omitempty"` -} - -type autoComplete struct { - AutoCompleteType string `json:"autoCompleteType"` - AutoCompleteKey string `json:"autoCompleteKey"` - AutoCompleteValues []autoCompleteValues `json:"autoCompleteValues"` - LookupFileName string `json:"lookupFileName"` - LookupLabelColumn string `json:"lookupLabelColumn"` - LookupValueColumn string `json:"lookupValueColumn"` -} - -type autoCompleteValues struct { - Label string `json:"label"` - Value string `json:"value"` -} - -type autoParsingInfo struct { - Mode string `json:"mode"` -} - -type coloringRulesDefinition struct { - Scope string `json:"scope"` - SingleSeriesAggregateFunction string `json:"singleSeriesAggregateFunction"` - MultipleSeriesAggregateFunction string `json:"multipleSeriesAggregateFunction"` - ColorThresholds colorThresholds `json:"colorThresholds"` -} - -type colorThresholds struct { - Color string `json:"color"` - Min int `json:"min"` - Max int `json:"max"` -} - -type contentSyncDefinition struct { - Type string `json:"type"` - Name string `json:"name"` -} - -type exportError struct { - Code string `json:"code,omitempty"` - Message string `json:"message,omitempty"` - Detail string `json:"detail,omitempty"` -} - -type fields struct { - FieldName string `json:"fieldName"` - FieldType string `json:"fieldType"` -} - -type filtersSyncDefinition struct { - FieldName string `json:"fieldName"` - Label string `json:"label"` - DefaultValue string `json:"defaultValue"` - FilterType string `json:"filterType"` - Properties string `json:"properties"` - PanelIds []string `json:"panelIds"` -} - -type layout struct { - LayoutType string `json:"layoutType"` - LayoutStructures []layoutStructure `json:"layoutStructures"` -} - -type layoutStructure struct { - Key string `json:"key"` - Structure string `json:"structure"` -} - -type metricsQueriesDefinition struct { - Query string `json:"query"` - RowId string `json:"rowId"` -} - -type moveErrors struct { - Code string `json:"code"` - Message string `json:"message"` -} - -type panelsDefinition struct { - Id string `json:"id"` - Key string `json:"key"` - Title string `json:"title"` - visualSettings string `json:"visualSettings"` - KeepVisualSettingsConsistentWithParent bool `json:"keepVisualSettingsConsistentWithParent"` - PanelType string `json:"panelType"` -} - -type queries struct { - QueryString string `json:"queryString"` - QueryType string `json:"queryType"` - QueryKey string `json:"queryKey"` -} - -type queryParameters struct { - Name string `json:"name"` - Label string `json:"label"` - Description string `json:"description"` - DataType string `json:"dataType"` - Value string `json:"value"` - AutoComplete autoComplete `json:"autoComplete"` -} - -type rootPanelDefinition struct { - Id string `json:"id"` - Key string `json:"key"` - Title string `json:"title"` - VisualSettings string `json:"visualSettings"` - KeepVisualSettingsConsistentWithParent bool `json:"keepVisualSettingsConsistentWithParent"` - PanelType string `json:"panelType"` - Layout layout `json:"layout"` - Panels []panelsDefinition `json:"panels"` - Variables []variablesDefinition `json:"variables"` - ColoringRules []coloringRulesDefinition `json:"coloringRules"` -} - -type reportPanelSyncDefinition struct { - Name string `json:"name"` - ViewerType string `json:"viewerType"` - DetailLevel int `json:"detailLevel"` - QueryString string `json:"queryString"` - MetricsQueries []metricsQueriesDefinition `json:"metricsQueries"` - TimeRange timeRangeDefinition `json:"timeRange"` - X int `json:"x"` - Y int `json:"y"` - Width int `json:"width"` - Height int `json:"height"` - Properties string `json:"properties"` - Id string `json:"id"` - DesiredQuantizationInSecs int `json:"desiredQuantizationInSecs"` - QueryParameters []queryParameters `json:"queryParameters"` - AutoParsingInfo autoParsingInfo `json:"autoParsingInfo"` -} - -type search struct { - QueryText string `json:"queryText"` - DefaultTimeRange string `json:"defaultTimeRange"` - ByReceiptTime bool `json:"byReceiptTime"` - ViewName string `json:"viewName"` - ViewStartTime string `json:"viewStartTime"` - QueryParameters []queryParameters `json:"queryParameters"` - ParsingMode string `json:"parsingMode"` -} - -type searchSchedule struct { - CronExpression string `json:"cronExpression"` - DisplayableTimeRange string `json:"displayableTimeRange"` - ParseableTimeRange timeRangeDefinition `json:"parseableTimeRange"` - TimeZone string `json:"timeZone"` - Threshold searchScheduleThreshold `json:"threshold"` - Notification searchScheduleNotification `json:"notification"` - ScheduleType string `json:"scheduleType"` - MuteErrorEmails bool `json:"muteErrorEmails"` - Parameters []searchScheduleParamters `json:"parameters"` -} - -type searchScheduleNotification struct { - TaskType string `json:"taskType"` -} - -type searchScheduleParamters struct { - Name string `json:"name"` - Value string `json:"value"` -} - -type searchScheduleThreshold struct { - ThresholdType string `json:"thresholdType"` - Operator string `json:"operator"` - Count int `json:"count"` -} - -type timeRangeDefinition struct { - Type string `json:"type"` - From timeRangeFromDefinition `json:"from"` -} - -type timeRangeFromDefinition struct { - Type string `json:"type"` - RelativeTime string `json:"relativeTime"` -} - -type topologyLabelMap struct { - Service []string `json:"service"` -} - -type variablesDefinition struct { - Id string `json:"id"` - Name string `json:"name"` - DisplayName string `json:"displayName"` - DefaultValue string `json:"defaultValue"` - SourceDefinition variablesSourceDefinition `json:"sourceDefinition"` - AllowMultiSelect bool `json:"allowMultiSelect"` - IncludeAllOption bool `json:"includeAllOption"` - HideFromUI bool `json:"hideFromUI"` -} - -type variablesSourceDefinition struct { - VariableSourceType string `json:"variableSourceType"` -} diff --git a/api/dashboards.go b/api/dashboards.go deleted file mode 100644 index 794fa346..00000000 --- a/api/dashboards.go +++ /dev/null @@ -1,32 +0,0 @@ -package api - -type CreateDashboard struct { - Title string `json:"title"` - Description string `json:"description"` - FolderId string `json:"folderId"` - TopologyLabelMap topologyLabelMap `json:"topologyLabelMap"` - Domain string `json:"domain"` - RefreshInterval int `json:"refreshInterval"` - TimeRange timeRangeDefinition `json:"timeRange"` - Panels []panelsDefinition `json:"panels"` - Layout layout `json:"layout"` - Variables []variablesDefinition `json:"variables"` - Theme string `json:"theme"` - ColoringRules []coloringRulesDefinition `json:"coloringRules"` -} - -type GetDashboard struct { - Title string `json:"title"` - Description string `json:"description"` - FolderId string `json:"folderId"` - TopologyLabelMap topologyLabelMap `json:"topologyLabelMap"` - Domain string `json:"domain"` - RefreshInterval int `json:"refreshInterval"` - TimeRange timeRangeDefinition `json:"timeRange"` - Panels []panelsDefinition `json:"panels"` - Layout layout `json:"layout"` - Variables []variablesDefinition `json:"variables"` - Theme string `json:"theme"` - ColoringRules []coloringRulesDefinition `json:"coloringRules"` - Id string `json:"id"` -} diff --git a/go.mod b/go.mod index 0c003e41..5fa3a88d 100644 --- a/go.mod +++ b/go.mod @@ -24,7 +24,7 @@ require ( github.com/spf13/cobra v1.1.1 github.com/spf13/viper v1.7.1 github.com/stretchr/testify v1.6.1 // indirect - github.com/wizedkyle/sumologic-go-sdk/service/cip v0.7.0 + github.com/wizedkyle/sumologic-go-sdk/service/cip v0.8.1-0.20210902095618-f1717b030ad5 golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad // indirect golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c golang.org/x/text v0.3.5 // indirect diff --git a/go.sum b/go.sum index 517d69c0..00d06c29 100644 --- a/go.sum +++ b/go.sum @@ -271,34 +271,14 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210717124945-956f29b89aa3 h1:kXR6wF+AIEWWUOz3yKsYy2f9Jo1lcf1xWxbYkq7P6RI= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210717124945-956f29b89aa3/go.mod h1:vOQqk5F8YEKsMREZsbWKdHAYcrYJsPOkAdhIi4hV0a0= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210718102247-12433ac10884 h1:d0lUWkQACSQo4WkkOxNf2c+oqxC3zCnx4x9WgK7YL4U= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210718102247-12433ac10884/go.mod h1:vOQqk5F8YEKsMREZsbWKdHAYcrYJsPOkAdhIi4hV0a0= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210718113302-16330c6738cd h1:3SygEbpkfptpV9GkgvdZ075xloh2kTMl3475cM6k88w= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210718113302-16330c6738cd/go.mod h1:vOQqk5F8YEKsMREZsbWKdHAYcrYJsPOkAdhIi4hV0a0= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210718114709-2892a42df92f h1:xxFogrUNhM0L3EDd2r6xogzE84dgjsT4PSdSIh3i2EM= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210718114709-2892a42df92f/go.mod h1:vOQqk5F8YEKsMREZsbWKdHAYcrYJsPOkAdhIi4hV0a0= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210718114951-8ef691258e35 h1:3frvUOYO7ox4Sd+ZyUgEjnKdGFRGJo4G5yWq+QqgOTk= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210718114951-8ef691258e35/go.mod h1:vOQqk5F8YEKsMREZsbWKdHAYcrYJsPOkAdhIi4hV0a0= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210718115214-93af131e1893 h1:bY/jvasOyveGDeZT0TJT1a0pFVp6TatFUj7/LC185Uw= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210718115214-93af131e1893/go.mod h1:vOQqk5F8YEKsMREZsbWKdHAYcrYJsPOkAdhIi4hV0a0= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210718115740-9dbe086eb85b h1:unJnuNmUSc/CNsmuAzZH5I9wkK+vW/RTBc8x32Tr02k= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210718115740-9dbe086eb85b/go.mod h1:vOQqk5F8YEKsMREZsbWKdHAYcrYJsPOkAdhIi4hV0a0= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210718120615-3cf938b90168 h1:Wvf1smU2ty7jYeP4HSQSACFXvZHdgVLSSIdaVoRNz0A= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210718120615-3cf938b90168/go.mod h1:vOQqk5F8YEKsMREZsbWKdHAYcrYJsPOkAdhIi4hV0a0= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210718120808-a3413f38d0b2 h1:rScEDAF1kmQQkD3UbGaXnC4T/teEyTQXiurmOToR4Ms= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210718120808-a3413f38d0b2/go.mod h1:vOQqk5F8YEKsMREZsbWKdHAYcrYJsPOkAdhIi4hV0a0= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210719054953-df65c0ae0857 h1:q71Y3i4FGVWzyMm4bALs8nsWpWxf9rNWDRAxG5CwpYY= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210719054953-df65c0ae0857/go.mod h1:vOQqk5F8YEKsMREZsbWKdHAYcrYJsPOkAdhIi4hV0a0= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210719055640-6952d06c0050 h1:+eE0WgLHzDXy8JOJF2H3hDSkOP98takQ2UtfUn2I00w= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210719055640-6952d06c0050/go.mod h1:vOQqk5F8YEKsMREZsbWKdHAYcrYJsPOkAdhIi4hV0a0= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210719061101-63492f3f5d32 h1:4Wpab62BXVjV8RP921MuWm5mSgMAO9ZUBPmH8RI7/QI= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210719061101-63492f3f5d32/go.mod h1:vOQqk5F8YEKsMREZsbWKdHAYcrYJsPOkAdhIi4hV0a0= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210719061942-806042656638 h1:4tBaTbQLL51r1DEsmtOUhtEDoPNJbjs1JKS5l3yBj0E= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210719061942-806042656638/go.mod h1:vOQqk5F8YEKsMREZsbWKdHAYcrYJsPOkAdhIi4hV0a0= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.7.0 h1:cdg72+DsU6jyBc5PVB+jI6wsxAjUaijyKh3PmabNFq0= -github.com/wizedkyle/sumologic-go-sdk/service/cip v0.7.0/go.mod h1:vOQqk5F8YEKsMREZsbWKdHAYcrYJsPOkAdhIi4hV0a0= +github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210825094727-8109f4536350 h1:NU8c26arg1JL4m3j2dzDIWG2x5I4tHnN25CY3q331IU= +github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210825094727-8109f4536350/go.mod h1:vOQqk5F8YEKsMREZsbWKdHAYcrYJsPOkAdhIi4hV0a0= +github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210829120411-11bcf861ac71 h1:BD0bQb6oYPTJ2RlsTbZI00r0yvGrIwYGTsrr/yCvu4s= +github.com/wizedkyle/sumologic-go-sdk/service/cip v0.6.1-0.20210829120411-11bcf861ac71/go.mod h1:vOQqk5F8YEKsMREZsbWKdHAYcrYJsPOkAdhIi4hV0a0= +github.com/wizedkyle/sumologic-go-sdk/service/cip v0.8.0 h1:ZYpZ/cH0U/IIm/5YHoostbYAw5Ua0NxwEdUrqzLmByM= +github.com/wizedkyle/sumologic-go-sdk/service/cip v0.8.0/go.mod h1:vOQqk5F8YEKsMREZsbWKdHAYcrYJsPOkAdhIi4hV0a0= +github.com/wizedkyle/sumologic-go-sdk/service/cip v0.8.1-0.20210902095618-f1717b030ad5 h1:r8xTM8ki9U3gOkkBYTRRoGb6GFwPZ8oJwIA8qAOxOTY= +github.com/wizedkyle/sumologic-go-sdk/service/cip v0.8.1-0.20210902095618-f1717b030ad5/go.mod h1:vOQqk5F8YEKsMREZsbWKdHAYcrYJsPOkAdhIi4hV0a0= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= diff --git a/pkg/cmd/access-keys/access-keys.go b/pkg/cmd/access-keys/access-keys.go index 8a6e7e2b..525306ab 100644 --- a/pkg/cmd/access-keys/access-keys.go +++ b/pkg/cmd/access-keys/access-keys.go @@ -1,26 +1,25 @@ package access_keys import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" cmdAccessKeysCreate "github.com/wizedkyle/sumocli/pkg/cmd/access-keys/create" cmdAccessKeysDelete "github.com/wizedkyle/sumocli/pkg/cmd/access-keys/delete" - cmdAccessKeysListAll "github.com/wizedkyle/sumocli/pkg/cmd/access-keys/list-all" - cmdAccessKeysListPersonal "github.com/wizedkyle/sumocli/pkg/cmd/access-keys/list-personal" + cmdAccessKeysListAll "github.com/wizedkyle/sumocli/pkg/cmd/access-keys/list_all" + cmdAccessKeysListPersonal "github.com/wizedkyle/sumocli/pkg/cmd/access-keys/list_personal" cmdAccessKeysUpdate "github.com/wizedkyle/sumocli/pkg/cmd/access-keys/update" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdAccessKeys(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAccessKeys(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "access-keys", Short: "Manage access keys", Long: "Commands that allow you to manage access keys in your Sumo Logic tenant", } - cmd.AddCommand(cmdAccessKeysCreate.NewCmdAccessKeysCreate(client, log)) - cmd.AddCommand(cmdAccessKeysDelete.NewCmdAccessKeysDelete(client, log)) - cmd.AddCommand(cmdAccessKeysListAll.NewCmdAccessKeysListAll(client, log)) - cmd.AddCommand(cmdAccessKeysListPersonal.NewCmdAccessKeysListPersonal(client, log)) - cmd.AddCommand(cmdAccessKeysUpdate.NewCmdAccessKeysUpdate(client, log)) + cmd.AddCommand(cmdAccessKeysCreate.NewCmdAccessKeysCreate(client)) + cmd.AddCommand(cmdAccessKeysDelete.NewCmdAccessKeysDelete(client)) + cmd.AddCommand(cmdAccessKeysListAll.NewCmdAccessKeysListAll(client)) + cmd.AddCommand(cmdAccessKeysListPersonal.NewCmdAccessKeysListPersonal(client)) + cmd.AddCommand(cmdAccessKeysUpdate.NewCmdAccessKeysUpdate(client)) return cmd } diff --git a/pkg/cmd/access-keys/create/create.go b/pkg/cmd/access-keys/create/create.go index d973cf25..a1a82367 100644 --- a/pkg/cmd/access-keys/create/create.go +++ b/pkg/cmd/access-keys/create/create.go @@ -1,14 +1,13 @@ package create import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdAccessKeysCreate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAccessKeysCreate(client *cip.APIClient) *cobra.Command { var ( name string corsHeaders []string @@ -17,7 +16,7 @@ func NewCmdAccessKeysCreate(client *cip.APIClient, log *zerolog.Logger) *cobra.C Use: "create", Short: "Creates a new access ID and key pair. The new access key can be used from the domains specified in corsHeaders field.", Run: func(cmd *cobra.Command, args []string) { - createAccessKey(name, corsHeaders, client, log) + createAccessKey(name, corsHeaders, client) }, } cmd.Flags().StringVar(&name, "name", "", "Specify a name for the access key") @@ -26,13 +25,13 @@ func NewCmdAccessKeysCreate(client *cip.APIClient, log *zerolog.Logger) *cobra.C return cmd } -func createAccessKey(name string, corsHeaders []string, client *cip.APIClient, log *zerolog.Logger) { +func createAccessKey(name string, corsHeaders []string, client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.CreateAccessKey(types.AccessKeyCreateRequest{ Label: name, CorsHeaders: corsHeaders, }) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to create access key") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/access-keys/delete/delete.go b/pkg/cmd/access-keys/delete/delete.go index a7cf74f2..a910ba9a 100644 --- a/pkg/cmd/access-keys/delete/delete.go +++ b/pkg/cmd/access-keys/delete/delete.go @@ -1,19 +1,18 @@ package delete import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdAccessKeysDelete(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAccessKeysDelete(client *cip.APIClient) *cobra.Command { var id string cmd := &cobra.Command{ Use: "delete", Short: "Deletes the access key with the given accessId.", Run: func(cmd *cobra.Command, args []string) { - deleteAccessKey(id, client, log) + deleteAccessKey(id, client) }, } cmd.Flags().StringVar(&id, "id", "", "Specify the id of the access key to delete") @@ -21,10 +20,10 @@ func NewCmdAccessKeysDelete(client *cip.APIClient, log *zerolog.Logger) *cobra.C return cmd } -func deleteAccessKey(id string, client *cip.APIClient, log *zerolog.Logger) { +func deleteAccessKey(id string, client *cip.APIClient) { httpResponse, errorResponse := client.DeleteAccessKey(id) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to delete access key") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(nil, httpResponse, errorResponse, "Access key was deleted successfully") } diff --git a/pkg/cmd/access-keys/list-all/list-all.go b/pkg/cmd/access-keys/list_all/list_all.go similarity index 68% rename from pkg/cmd/access-keys/list-all/list-all.go rename to pkg/cmd/access-keys/list_all/list_all.go index 7b515b66..93eb6f99 100644 --- a/pkg/cmd/access-keys/list-all/list-all.go +++ b/pkg/cmd/access-keys/list_all/list_all.go @@ -2,48 +2,47 @@ package list_all import ( "github.com/antihax/optional" - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdAccessKeysListAll(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAccessKeysListAll(client *cip.APIClient) *cobra.Command { var limit int32 cmd := &cobra.Command{ Use: "list-all", Short: "List all access keys in your account.", Run: func(cmd *cobra.Command, args []string) { - listAllAccessKeys(limit, client, log) + listAllAccessKeys(limit, client) }, } cmd.Flags().Int32Var(&limit, "limit", 100, "Specify the number of access keys returned") return cmd } -func listAllAccessKeys(limit int32, client *cip.APIClient, log *zerolog.Logger) { - var options types.AccessKeyManagementApiListAccessKeysOpts +func listAllAccessKeys(limit int32, client *cip.APIClient) { + var options types.AccessKeyOpts var paginationToken string options.Limit = optional.NewInt32(limit) apiResponse, httpResponse, errorResponse := client.ListAccessKeys(&options) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to list access keys") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } paginationToken = apiResponse.Next for paginationToken != "" { - apiResponse = listAllAccessKeysPagination(client, options, paginationToken, log) + apiResponse = listAllAccessKeysPagination(client, options, paginationToken) paginationToken = apiResponse.Next } } -func listAllAccessKeysPagination(client *cip.APIClient, options types.AccessKeyManagementApiListAccessKeysOpts, token string, log *zerolog.Logger) types.PaginatedListAccessKeysResult { +func listAllAccessKeysPagination(client *cip.APIClient, options types.AccessKeyOpts, token string) types.PaginatedListAccessKeysResult { options.Token = optional.NewString(token) apiResponse, httpResponse, errorResponse := client.ListAccessKeys(&options) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to list access keys") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/access-keys/list-personal/list-personal.go b/pkg/cmd/access-keys/list_personal/list_personal.go similarity index 62% rename from pkg/cmd/access-keys/list-personal/list-personal.go rename to pkg/cmd/access-keys/list_personal/list_personal.go index 362d583d..7922cefb 100644 --- a/pkg/cmd/access-keys/list-personal/list-personal.go +++ b/pkg/cmd/access-keys/list_personal/list_personal.go @@ -1,27 +1,26 @@ package list_personal import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdAccessKeysListPersonal(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAccessKeysListPersonal(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "list-personal", Short: "List all access keys that belong to your user.", Run: func(cmd *cobra.Command, args []string) { - listPersonalAccessKeys(client, log) + listPersonalAccessKeys(client) }, } return cmd } -func listPersonalAccessKeys(client *cip.APIClient, log *zerolog.Logger) { +func listPersonalAccessKeys(client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.ListPersonalAccessKeys() if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to list personal access keys") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/access-keys/update/update.go b/pkg/cmd/access-keys/update/update.go index b42fae4d..1f14ec52 100644 --- a/pkg/cmd/access-keys/update/update.go +++ b/pkg/cmd/access-keys/update/update.go @@ -1,14 +1,13 @@ package update import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdAccessKeysUpdate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAccessKeysUpdate(client *cip.APIClient) *cobra.Command { var ( corsHeaders []string disabled bool @@ -18,7 +17,7 @@ func NewCmdAccessKeysUpdate(client *cip.APIClient, log *zerolog.Logger) *cobra.C Use: "update", Short: "Updates the properties of existing accessKey by accessId. It can be used to enable or disable the access key and to update the corsHeaders list.", Run: func(cmd *cobra.Command, args []string) { - updateAccessKey(corsHeaders, disabled, id, client, log) + updateAccessKey(corsHeaders, disabled, id, client) }, } cmd.Flags().StringSliceVar(&corsHeaders, "corsHeaders", []string{}, "Specify cors headers (they need to be comma separated e.g. header1,header2,header3 and be valid URLs e.g. https://test.com)") @@ -28,14 +27,14 @@ func NewCmdAccessKeysUpdate(client *cip.APIClient, log *zerolog.Logger) *cobra.C return cmd } -func updateAccessKey(corsHeaders []string, disabled bool, id string, client *cip.APIClient, log *zerolog.Logger) { +func updateAccessKey(corsHeaders []string, disabled bool, id string, client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.UpdateAccessKey(types.AccessKeyUpdateRequest{ Disabled: disabled, CorsHeaders: corsHeaders, }, id) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to update access key") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/account/account.go b/pkg/cmd/account/account.go index 430bcb47..d85c8b2e 100644 --- a/pkg/cmd/account/account.go +++ b/pkg/cmd/account/account.go @@ -1,7 +1,6 @@ package account import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" NewCmdAccountCreateSubdomain "github.com/wizedkyle/sumocli/pkg/cmd/account/create-subdomain" NewCmdAccountDeleteSubdomain "github.com/wizedkyle/sumocli/pkg/cmd/account/delete-subdomain" @@ -12,17 +11,17 @@ import ( "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdAccount(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAccount(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "account", Short: "Manage account settings", Long: "Commands that allow you to manage your Sumo Logic account settings", } - cmd.AddCommand(NewCmdAccountCreateSubdomain.NewCmdAccountCreateSubdomain(client, log)) - cmd.AddCommand(NewCmdAccountDeleteSubdomain.NewCmdAccountDeleteSubdomain(client, log)) - cmd.AddCommand(NewCmdAccountGetOwner.NewCmdAccountGetOwner(client, log)) - cmd.AddCommand(NewCmdAccountGetSubdomain.NewCmdAccountGetSubdomain(client, log)) - cmd.AddCommand(NewCmdAccountRecoverSubdomain.NewCmdAccountRecoverSubdomain(client, log)) - cmd.AddCommand(NewCmdAccountUpdateSubdomain.NewCmdAccountUpdateSubdomain(client, log)) + cmd.AddCommand(NewCmdAccountCreateSubdomain.NewCmdAccountCreateSubdomain(client)) + cmd.AddCommand(NewCmdAccountDeleteSubdomain.NewCmdAccountDeleteSubdomain(client)) + cmd.AddCommand(NewCmdAccountGetOwner.NewCmdAccountGetOwner(client)) + cmd.AddCommand(NewCmdAccountGetSubdomain.NewCmdAccountGetSubdomain(client)) + cmd.AddCommand(NewCmdAccountRecoverSubdomain.NewCmdAccountRecoverSubdomain(client)) + cmd.AddCommand(NewCmdAccountUpdateSubdomain.NewCmdAccountUpdateSubdomain(client)) return cmd } diff --git a/pkg/cmd/account/create-subdomain/create-subdomain.go b/pkg/cmd/account/create-subdomain/create-subdomain.go index 7dfa4ce3..6245563b 100644 --- a/pkg/cmd/account/create-subdomain/create-subdomain.go +++ b/pkg/cmd/account/create-subdomain/create-subdomain.go @@ -1,20 +1,19 @@ package create_subdomain import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdAccountCreateSubdomain(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAccountCreateSubdomain(client *cip.APIClient) *cobra.Command { var subdomain string cmd := &cobra.Command{ Use: "create-subdomain", Short: "Create a subdomain. Only the Account Owner can create a subdomain.", Run: func(cmd *cobra.Command, args []string) { - createSubdomain(subdomain, client, log) + createSubdomain(subdomain, client) }, } cmd.Flags().StringVar(&subdomain, "subdomain", "", "Specify a subdomain (minimum 4 and maximum 63 characters)") @@ -22,12 +21,12 @@ func NewCmdAccountCreateSubdomain(client *cip.APIClient, log *zerolog.Logger) *c return cmd } -func createSubdomain(subdomain string, client *cip.APIClient, log *zerolog.Logger) { +func createSubdomain(subdomain string, client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.CreateSubdomain(types.ConfigureSubdomainRequest{ Subdomain: subdomain, }) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to create subdomain") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/account/delete-subdomain/delete-subdomain.go b/pkg/cmd/account/delete-subdomain/delete-subdomain.go index b5b8c115..1d95bacb 100644 --- a/pkg/cmd/account/delete-subdomain/delete-subdomain.go +++ b/pkg/cmd/account/delete-subdomain/delete-subdomain.go @@ -1,27 +1,26 @@ package delete_subdomain import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdAccountDeleteSubdomain(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAccountDeleteSubdomain(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "delete-subdomain", Short: "Delete the configured subdomain.", Run: func(cmd *cobra.Command, args []string) { - deleteSubdomain(client, log) + deleteSubdomain(client) }, } return cmd } -func deleteSubdomain(client *cip.APIClient, log *zerolog.Logger) { +func deleteSubdomain(client *cip.APIClient) { httpResponse, errorResponse := client.DeleteSubdomain() if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to delete subdomain") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(nil, httpResponse, errorResponse, "The subdomain was successfully deleted.") } diff --git a/pkg/cmd/account/get-owner/get-owner.go b/pkg/cmd/account/get-owner/get-owner.go index 6d2eb3b8..549f4691 100644 --- a/pkg/cmd/account/get-owner/get-owner.go +++ b/pkg/cmd/account/get-owner/get-owner.go @@ -1,31 +1,30 @@ package get_owner import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdAccountGetOwner(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAccountGetOwner(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "get-owner", Short: "Returns the user identifier as the account owner.", Run: func(cmd *cobra.Command, args []string) { - getOwner(client, log) + getOwner(client) }, } return cmd } -func getOwner(client *cip.APIClient, log *zerolog.Logger) { - userId, _, errorResponse := client.GetAccountOwner() +func getOwner(client *cip.APIClient) { + userId, httpResponse, errorResponse := client.GetAccountOwner() if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to get account owner") + cmdutils.OutputError(httpResponse, errorResponse) } else { userResponse, httpResponse, errorResponse := client.GetUser(userId) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to get user") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(userResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/account/get-subdomain/get-subdomain.go b/pkg/cmd/account/get-subdomain/get-subdomain.go index 6dff9c6d..8d7a0de5 100644 --- a/pkg/cmd/account/get-subdomain/get-subdomain.go +++ b/pkg/cmd/account/get-subdomain/get-subdomain.go @@ -1,27 +1,26 @@ package get_subdomain import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdAccountGetSubdomain(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAccountGetSubdomain(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "get-subdomain", Short: "Get the configured subdomain.", Run: func(cmd *cobra.Command, args []string) { - getSubdomain(client, log) + getSubdomain(client) }, } return cmd } -func getSubdomain(client *cip.APIClient, log *zerolog.Logger) { +func getSubdomain(client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.GetSubdomain() if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to get subdomain") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/account/recover-subdomain/recover-subdomain.go b/pkg/cmd/account/recover-subdomain/recover-subdomain.go index 4ee27817..a7140ca5 100644 --- a/pkg/cmd/account/recover-subdomain/recover-subdomain.go +++ b/pkg/cmd/account/recover-subdomain/recover-subdomain.go @@ -1,19 +1,18 @@ package recover_subdomain import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdAccountRecoverSubdomain(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAccountRecoverSubdomain(client *cip.APIClient) *cobra.Command { var email string cmd := &cobra.Command{ Use: "recover-subdomain", Short: "Send an email with the subdomain information for a user with the given email address.", Run: func(cmd *cobra.Command, args []string) { - recoverSubdomain(email, client, log) + recoverSubdomain(email, client) }, } cmd.Flags().StringVar(&email, "email", "", "Specify an email address of the user to get subdomain information") @@ -21,10 +20,10 @@ func NewCmdAccountRecoverSubdomain(client *cip.APIClient, log *zerolog.Logger) * return cmd } -func recoverSubdomain(email string, client *cip.APIClient, log *zerolog.Logger) { +func recoverSubdomain(email string, client *cip.APIClient) { httpResponse, errorResponse := client.RecoverSubdomains(email) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to recover subdomain") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(nil, httpResponse, errorResponse, "An email containing information about associated subdomains for the given email was sent.") } diff --git a/pkg/cmd/account/update-subdomain/update-subdomain.go b/pkg/cmd/account/update-subdomain/update-subdomain.go index ed9d4a5e..5f6c4abd 100644 --- a/pkg/cmd/account/update-subdomain/update-subdomain.go +++ b/pkg/cmd/account/update-subdomain/update-subdomain.go @@ -1,20 +1,19 @@ package update_subdomain import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdAccountUpdateSubdomain(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAccountUpdateSubdomain(client *cip.APIClient) *cobra.Command { var subdomain string cmd := &cobra.Command{ Use: "update-subdomain", Short: "Update a subdomain. Only the Account Owner can update the subdomain.", Run: func(cmd *cobra.Command, args []string) { - updateSubdomain(subdomain, client, log) + updateSubdomain(subdomain, client) }, } cmd.Flags().StringVar(&subdomain, "subdomain", "", "Specify a new subdomain (minimum 4 and maximum 63 characters)") @@ -22,12 +21,12 @@ func NewCmdAccountUpdateSubdomain(client *cip.APIClient, log *zerolog.Logger) *c return cmd } -func updateSubdomain(subdomain string, client *cip.APIClient, log *zerolog.Logger) { +func updateSubdomain(subdomain string, client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.UpdateSubdomain(types.ConfigureSubdomainRequest{ Subdomain: subdomain, }) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to update subdomain") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/apps/apps.go b/pkg/cmd/apps/apps.go index 7cb3308f..339bd4f1 100644 --- a/pkg/cmd/apps/apps.go +++ b/pkg/cmd/apps/apps.go @@ -1,7 +1,6 @@ package apps import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" NewCmdAppsGet "github.com/wizedkyle/sumocli/pkg/cmd/apps/get" NewCmdAppsInstall "github.com/wizedkyle/sumocli/pkg/cmd/apps/install" @@ -10,15 +9,15 @@ import ( "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdApps(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdApps(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "apps", Short: "Manage apps (Beta)", Long: "View and install Sumo Logic Applications that deliver out-of-the-box dashboards, saved searches, and field extraction for popular data sources.", } - cmd.AddCommand(NewCmdAppsGet.NewCmdAppsGet(client, log)) - cmd.AddCommand(NewCmdAppsInstall.NewCmdAppsInstall(client, log)) - cmd.AddCommand(NewCmdAppsInstallStatus.NewCmdAppsInstallStatus(client, log)) - cmd.AddCommand(NewCmdAppsList.NewCmdAppsList(client, log)) + cmd.AddCommand(NewCmdAppsGet.NewCmdAppsGet(client)) + cmd.AddCommand(NewCmdAppsInstall.NewCmdAppsInstall(client)) + cmd.AddCommand(NewCmdAppsInstallStatus.NewCmdAppsInstallStatus(client)) + cmd.AddCommand(NewCmdAppsList.NewCmdAppsList(client)) return cmd } diff --git a/pkg/cmd/apps/get/get.go b/pkg/cmd/apps/get/get.go index 253c9ac0..09da3335 100644 --- a/pkg/cmd/apps/get/get.go +++ b/pkg/cmd/apps/get/get.go @@ -1,19 +1,18 @@ package get import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdAppsGet(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAppsGet(client *cip.APIClient) *cobra.Command { var uuid string cmd := &cobra.Command{ Use: "get", Short: "Gets the app with the given universally unique identifier (UUID).", Run: func(cmd *cobra.Command, args []string) { - getApp(uuid, client, log) + getApp(uuid, client) }, } cmd.Flags().StringVar(&uuid, "uuid", "", "Specify the UUID of the app") @@ -21,10 +20,10 @@ func NewCmdAppsGet(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { return cmd } -func getApp(uuid string, client *cip.APIClient, log *zerolog.Logger) { +func getApp(uuid string, client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.GetApp(uuid) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to get app") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/apps/install/install.go b/pkg/cmd/apps/install/install.go index bf011039..47a2e34e 100644 --- a/pkg/cmd/apps/install/install.go +++ b/pkg/cmd/apps/install/install.go @@ -1,14 +1,13 @@ package install import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdAppsInstall(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAppsInstall(client *cip.APIClient) *cobra.Command { var ( destinationFolderId string description string @@ -20,7 +19,7 @@ func NewCmdAppsInstall(client *cip.APIClient, log *zerolog.Logger) *cobra.Comman Use: "install", Short: "Installs the app with given UUID in the folder specified.", Run: func(cmd *cobra.Command, args []string) { - installApp(destinationFolderId, description, logSource, name, uuid, client, log) + installApp(destinationFolderId, description, logSource, name, uuid, client) }, } cmd.Flags().StringVar(&destinationFolderId, "destinationFolderId", "", "Specify the folder id that the app should be installed into") @@ -35,7 +34,7 @@ func NewCmdAppsInstall(client *cip.APIClient, log *zerolog.Logger) *cobra.Comman return cmd } -func installApp(destinationFolderId string, description string, logSource string, name string, uuid string, client *cip.APIClient, log *zerolog.Logger) { +func installApp(destinationFolderId string, description string, logSource string, name string, uuid string, client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.InstallApp(types.AppInstallRequest{ Name: name, Description: description, @@ -46,7 +45,7 @@ func installApp(destinationFolderId string, description string, logSource string }, uuid) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to install app") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/apps/install_status/install_status.go b/pkg/cmd/apps/install_status/install_status.go index fecee5b1..d9707a08 100644 --- a/pkg/cmd/apps/install_status/install_status.go +++ b/pkg/cmd/apps/install_status/install_status.go @@ -1,19 +1,18 @@ package install_status import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdAppsInstallStatus(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAppsInstallStatus(client *cip.APIClient) *cobra.Command { var jobId string cmd := &cobra.Command{ Use: "install-status", Short: "Get the status of an asynchronous app install request for the given job identifier.", Run: func(cmd *cobra.Command, args []string) { - getAppInstallStatus(jobId, client, log) + getAppInstallStatus(jobId, client) }, } cmd.Flags().StringVar(&jobId, "jobId", "", "Specify a jobId (it can be retrieved by running sumocli apps install)") @@ -21,10 +20,10 @@ func NewCmdAppsInstallStatus(client *cip.APIClient, log *zerolog.Logger) *cobra. return cmd } -func getAppInstallStatus(jobId string, client *cip.APIClient, log *zerolog.Logger) { +func getAppInstallStatus(jobId string, client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.GetAsyncInstallStatus(jobId) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to get install status") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/apps/list/list.go b/pkg/cmd/apps/list/list.go index 176c015a..e7c2c508 100644 --- a/pkg/cmd/apps/list/list.go +++ b/pkg/cmd/apps/list/list.go @@ -1,27 +1,26 @@ package list import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdAppsList(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAppsList(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "list", Short: "Lists all available apps from the App Catalog.", Run: func(cmd *cobra.Command, args []string) { - listAvailableApps(client, log) + listAvailableApps(client) }, } return cmd } -func listAvailableApps(client *cip.APIClient, log *zerolog.Logger) { +func listAvailableApps(client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.ListApps() if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to list apps") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/archive-ingestion/archive-ingestion.go b/pkg/cmd/archive-ingestion/archive-ingestion.go index d21fbc06..6614995f 100644 --- a/pkg/cmd/archive-ingestion/archive-ingestion.go +++ b/pkg/cmd/archive-ingestion/archive-ingestion.go @@ -1,7 +1,6 @@ package archive_ingestion import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" NewCmdArchiveIngestionCreate "github.com/wizedkyle/sumocli/pkg/cmd/archive-ingestion/create" NewCmdArchiveIngestionDelete "github.com/wizedkyle/sumocli/pkg/cmd/archive-ingestion/delete" @@ -10,16 +9,16 @@ import ( "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdArchiveIngestion(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdArchiveIngestion(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "archive-ingestion", Short: "Manages archive ingestion", Long: "Archive Ingestion allows you to ingest data from Archive destinations. " + "You can use this command to ingest data from your Archive with an existing AWS S3 Archive Source.", } - cmd.AddCommand(NewCmdArchiveIngestionCreate.NewCmdArchiveIngestionCreate(client, log)) - cmd.AddCommand(NewCmdArchiveIngestionDelete.NewCmdArchiveIngestionDelete(client, log)) - cmd.AddCommand(NewCmdArchiveIngestionGet.NewCmdArchiveIngestionGet(client, log)) - cmd.AddCommand(NewCmdArchiveIngestionList.NewCmdArchiveIngestionList(client, log)) + cmd.AddCommand(NewCmdArchiveIngestionCreate.NewCmdArchiveIngestionCreate(client)) + cmd.AddCommand(NewCmdArchiveIngestionDelete.NewCmdArchiveIngestionDelete(client)) + cmd.AddCommand(NewCmdArchiveIngestionGet.NewCmdArchiveIngestionGet(client)) + cmd.AddCommand(NewCmdArchiveIngestionList.NewCmdArchiveIngestionList(client)) return cmd } diff --git a/pkg/cmd/archive-ingestion/create/create.go b/pkg/cmd/archive-ingestion/create/create.go index 752dc829..1434dfc0 100644 --- a/pkg/cmd/archive-ingestion/create/create.go +++ b/pkg/cmd/archive-ingestion/create/create.go @@ -1,7 +1,7 @@ package create import ( - "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" @@ -9,7 +9,7 @@ import ( "time" ) -func NewCmdArchiveIngestionCreate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdArchiveIngestionCreate(client *cip.APIClient) *cobra.Command { var ( endTime string name string @@ -20,7 +20,7 @@ func NewCmdArchiveIngestionCreate(client *cip.APIClient, log *zerolog.Logger) *c Use: "create", Short: "Create an ingestion job to pull data from your S3 bucket.", Run: func(cmd *cobra.Command, args []string) { - createArchiveIngestion(endTime, name, sourceId, startTime, client, log) + createArchiveIngestion(endTime, name, sourceId, startTime, client) }, } cmd.Flags().StringVar(&endTime, "endTime", "", "Specify the ending timestamp of the ingestion job. "+ @@ -37,7 +37,7 @@ func NewCmdArchiveIngestionCreate(client *cip.APIClient, log *zerolog.Logger) *c return cmd } -func createArchiveIngestion(endTime string, name string, sourceId string, startTime string, client *cip.APIClient, log *zerolog.Logger) { +func createArchiveIngestion(endTime string, name string, sourceId string, startTime string, client *cip.APIClient) { format := "2006-01-02T15:04:05Z" endTimeParsed, err := time.Parse(format, endTime) if err != nil { @@ -54,7 +54,7 @@ func createArchiveIngestion(endTime string, name string, sourceId string, startT }, sourceId) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to create archive job") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/archive-ingestion/delete/delete.go b/pkg/cmd/archive-ingestion/delete/delete.go index 5c378738..84aab380 100644 --- a/pkg/cmd/archive-ingestion/delete/delete.go +++ b/pkg/cmd/archive-ingestion/delete/delete.go @@ -1,13 +1,12 @@ package delete import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdArchiveIngestionDelete(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdArchiveIngestionDelete(client *cip.APIClient) *cobra.Command { var ( id string sourceId string @@ -17,7 +16,7 @@ func NewCmdArchiveIngestionDelete(client *cip.APIClient, log *zerolog.Logger) *c Short: "Delete an ingestion job with the given identifier from the organization. " + "The delete operation is only possible for jobs with a Succeeded or Failed status.", Run: func(cmd *cobra.Command, args []string) { - deleteArchiveIngestion(id, sourceId, client, log) + deleteArchiveIngestion(id, sourceId, client) }, } cmd.Flags().StringVar(&id, "id", "", "Specify the id of the archive source") @@ -27,10 +26,10 @@ func NewCmdArchiveIngestionDelete(client *cip.APIClient, log *zerolog.Logger) *c return cmd } -func deleteArchiveIngestion(id string, sourceId string, client *cip.APIClient, log *zerolog.Logger) { +func deleteArchiveIngestion(id string, sourceId string, client *cip.APIClient) { httpResponse, errorResponse := client.DeleteArchiveJob(sourceId, id) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to delete archive job") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(nil, httpResponse, errorResponse, "The ingestion job was deleted successfully.") } diff --git a/pkg/cmd/archive-ingestion/get/get.go b/pkg/cmd/archive-ingestion/get/get.go index 7e08bcc1..24e5417f 100644 --- a/pkg/cmd/archive-ingestion/get/get.go +++ b/pkg/cmd/archive-ingestion/get/get.go @@ -2,14 +2,13 @@ package get import ( "github.com/antihax/optional" - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdArchiveIngestionGet(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdArchiveIngestionGet(client *cip.APIClient) *cobra.Command { var ( limit int32 sourceId string @@ -19,7 +18,7 @@ func NewCmdArchiveIngestionGet(client *cip.APIClient, log *zerolog.Logger) *cobr Use: "get", Short: "Get a list of all the ingestion jobs created on an Archive Source.", Run: func(cmd *cobra.Command, args []string) { - getArchiveIngestion(limit, sourceId, client, log) + getArchiveIngestion(limit, sourceId, client) }, } cmd.Flags().Int32Var(&limit, "limit", 10, "Specify the number of jobs to return") @@ -28,28 +27,28 @@ func NewCmdArchiveIngestionGet(client *cip.APIClient, log *zerolog.Logger) *cobr return cmd } -func getArchiveIngestion(limit int32, sourceId string, client *cip.APIClient, log *zerolog.Logger) { - var options types.ArchiveManagementApiListArchiveJobsBySourceIdOpts +func getArchiveIngestion(limit int32, sourceId string, client *cip.APIClient) { + var options types.ArchiveOpts var paginationToken string options.Limit = optional.NewInt32(limit) apiResponse, httpResponse, errorResponse := client.ListArchiveJobsBySourceId(sourceId, &options) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to list archive jobs by source id") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } paginationToken = apiResponse.Next for paginationToken != "" { - apiResponse = getArchiveIngestionPagination(client, options, paginationToken, sourceId, log) + apiResponse = getArchiveIngestionPagination(client, options, paginationToken, sourceId) paginationToken = apiResponse.Next } } -func getArchiveIngestionPagination(client *cip.APIClient, options types.ArchiveManagementApiListArchiveJobsBySourceIdOpts, token string, sourceId string, log *zerolog.Logger) types.ListArchiveJobsResponse { +func getArchiveIngestionPagination(client *cip.APIClient, options types.ArchiveOpts, token string, sourceId string) types.ListArchiveJobsResponse { options.Token = optional.NewString(token) apiResponse, httpResponse, errorResponse := client.ListArchiveJobsBySourceId(sourceId, &options) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to list archive jobs by source id") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/archive-ingestion/list/list.go b/pkg/cmd/archive-ingestion/list/list.go index 69f4e447..86b7616d 100644 --- a/pkg/cmd/archive-ingestion/list/list.go +++ b/pkg/cmd/archive-ingestion/list/list.go @@ -1,27 +1,26 @@ package list import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdArchiveIngestionList(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdArchiveIngestionList(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "list", Short: "Get a list of all Archive Sources with the count and status of ingestion jobs.", Run: func(cmd *cobra.Command, args []string) { - listArchiveIngestion(client, log) + listArchiveIngestion(client) }, } return cmd } -func listArchiveIngestion(client *cip.APIClient, log *zerolog.Logger) { +func listArchiveIngestion(client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.ListArchiveJobsCountPerSource() if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to list archive jobs") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/collectors/collectors.go b/pkg/cmd/collectors/collectors.go index 5bf5eaf2..e4e1abc5 100644 --- a/pkg/cmd/collectors/collectors.go +++ b/pkg/cmd/collectors/collectors.go @@ -8,19 +8,20 @@ import ( cmdCollectorList "github.com/wizedkyle/sumocli/pkg/cmd/collectors/list" cmdCollectorUpdate "github.com/wizedkyle/sumocli/pkg/cmd/collectors/update" cmdCollectorUpgrade "github.com/wizedkyle/sumocli/pkg/cmd/collectors/upgrade" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdCollectors() *cobra.Command { +func NewCmdCollectors(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "collectors ", Short: "Manages collectors", } - cmd.AddCommand(cmdCollectorCreate.NewCmdCollectorCreate()) - cmd.AddCommand(cmdCollectorDelete.NewCmdCollectorDelete()) - cmd.AddCommand(cmdCollectorGet.NewCmdCollectorGet()) - cmd.AddCommand(cmdCollectorList.NewCmdCollectorList()) - cmd.AddCommand(cmdCollectorUpdate.NewCmdCollectorUpdate()) - cmd.AddCommand(cmdCollectorUpgrade.NewCmdUpgradeCollectors()) + cmd.AddCommand(cmdCollectorCreate.NewCmdCollectorCreate(client)) + cmd.AddCommand(cmdCollectorDelete.NewCmdCollectorDelete(client)) + cmd.AddCommand(cmdCollectorGet.NewCmdCollectorGet(client)) + cmd.AddCommand(cmdCollectorList.NewCmdCollectorList(client)) + cmd.AddCommand(cmdCollectorUpdate.NewCmdCollectorUpdate(client)) + cmd.AddCommand(cmdCollectorUpgrade.NewCmdUpgradeCollectors(client)) return cmd } diff --git a/pkg/cmd/collectors/create/create.go b/pkg/cmd/collectors/create/create.go index 74237619..f1665f4a 100644 --- a/pkg/cmd/collectors/create/create.go +++ b/pkg/cmd/collectors/create/create.go @@ -1,77 +1,53 @@ package create import ( - "encoding/json" "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "strings" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdCollectorCreate() *cobra.Command { +func NewCmdCollectorCreate(client *cip.APIClient) *cobra.Command { var ( name string description string category string - fields string + fieldNames []string + fieldValues []string ) cmd := &cobra.Command{ Use: "create", Short: "Creates a Sumo Logic Hosted Collector", Run: func(cmd *cobra.Command, args []string) { - Collector(name, description, category, fields) + Collector(name, description, category, fieldNames, fieldValues, client) }, } - cmd.Flags().StringVar(&name, "name", "", "Specify the name of the collector") cmd.Flags().StringVar(&description, "description", "", "Specify a description for the collector") cmd.Flags().StringVar(&category, "category", "", "sourceCategory for the collector, this will overwrite the categories on configured sources") + cmd.Flags().StringSliceVar(&fieldNames, "fieldNames", []string{}, "Specify the names of fields to add to the collector "+ + "{names need to be comma separated e.g. field1,field2") + cmd.Flags().StringSliceVar(&fieldValues, "fieldValues", []string{}, "Specify the values of fields to add to the collector "+ + "(values need to be comma separated e.g. value1,value2") + cmd.MarkFlagRequired("name") return cmd } -func Collector(name string, description string, category string, fields string) api.CollectorResponse { - log := logging.GetConsoleLogger() - var createCollectorResponse api.CollectorResponse - requestBodySchema := &api.CreateCollectorRequest{ - Collector: api.CreateCollector{ +func Collector(name string, description string, category string, fieldNames []string, fieldValues []string, client *cip.APIClient) { + fields := cmdutils.GenerateFieldsMap(fieldNames, fieldValues) + apiResponse, httpResponse, errorResponse := client.CreateCollector(types.CreateCollectorRequest{ + Collector: types.CreateCollectorRequestDefinition{ CollectorType: "Hosted", Name: name, Description: description, Category: category, - Fields: nil, + Fields: fields, }, + }) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } - - if fields != "" { - fieldsMap := make(map[string]string) - splitStrings := strings.Split(fields, ",") - for i, splitString := range splitStrings { - components := strings.Split(splitString, ":") - fieldsMap[components[0]] = components[1] - i++ - } - requestBodySchema.Collector.Fields = fieldsMap - } - - requestBody, _ := json.Marshal(requestBodySchema) - client, request := factory.NewHttpRequestWithBody("POST", "/v1/collectors", requestBody) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("error reading response body from request") - } - - err = json.Unmarshal(responseBody, &createCollectorResponse) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - return createCollectorResponse } diff --git a/pkg/cmd/collectors/delete/delete.go b/pkg/cmd/collectors/delete/delete.go index 03f916c0..a6d948ca 100644 --- a/pkg/cmd/collectors/delete/delete.go +++ b/pkg/cmd/collectors/delete/delete.go @@ -1,99 +1,48 @@ package delete import ( - "fmt" - "github.com/manifoldco/promptui" + "github.com/antihax/optional" "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "net/url" - "strconv" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdCollectorDelete() *cobra.Command { +func NewCmdCollectorDelete(client *cip.APIClient) *cobra.Command { var ( - aliveBeforeDays int - force bool + aliveBeforeDays int32 id string offline bool ) - cmd := &cobra.Command{ Use: "delete", Short: "Deletes a Sumo Logic collector", Run: func(cmd *cobra.Command, args []string) { - deleteCollector(aliveBeforeDays, force, id, offline) + deleteCollector(aliveBeforeDays, id, offline, client) }, } - - cmd.Flags().IntVar(&aliveBeforeDays, "aliveBeforeDays", 100, "Minimum number of days the collectors have been offline") - cmd.Flags().BoolVar(&force, "force", false, "Forces removal of offline collectors useful for CI/CD pipelines") + cmd.Flags().Int32Var(&aliveBeforeDays, "aliveBeforeDays", 100, "Minimum number of days the collectors have been offline") cmd.Flags().StringVar(&id, "id", "", "Specify the id of the collector to delete") cmd.Flags().BoolVar(&offline, "offline", false, "Removes all offline collectors") return cmd } -func deleteCollector(aliveBeforeDays int, force bool, id string, offline bool) { - log := logging.GetConsoleLogger() - if offline == true { - if force == true { - requestUrl := "/v1/collectors/offline" - client, request := factory.NewHttpRequest("DELETE", requestUrl) - query := url.Values{} - query.Add("aliveBeforeDays", strconv.Itoa(aliveBeforeDays)) - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - defer response.Body.Close() - if response.StatusCode == 200 { - log.Info().Msg("offline collectors have been deleted") - } else { - log.Error().Msg("failed to delete offline collectors") - } - } else if force == false { - promptConfirm := promptui.Prompt{ - Label: "Confirm that you want to delete all offline collectors?", - IsConfirm: true, - } - _, err := promptConfirm.Run() - if err != nil { - log.Fatal().Err(err).Msg("failed to perform confirmation") - } - - requestUrl := "/v1/collectors/offline" - client, request := factory.NewHttpRequest("DELETE", requestUrl) - query := url.Values{} - query.Add("aliveBeforeDays", strconv.Itoa(aliveBeforeDays)) - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - defer response.Body.Close() - if response.StatusCode == 200 { - log.Info().Msg("offline collectors have been deleted") - } else { - log.Error().Msg("failed to delete offline collectors") - } - } - } else if offline == false { - if id == "" { - log.Fatal().Msg("a valid collector id needs to be provided, you can run sumocli collectors list to get ids") - } - - requestUrl := "/v1/collectors/" + id - client, request := factory.NewHttpRequest("DELETE", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) +func deleteCollector(aliveBeforeDays int32, id string, offline bool, client *cip.APIClient) { + if id != "" { + httpResponse, errorResponse := client.DeleteCollectorById(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(nil, httpResponse, errorResponse, "Collector with id "+id+" has been deleted") } - defer response.Body.Close() - if response.StatusCode == 200 { - fmt.Println("collector with id " + id + " has been deleted") + } else if offline == true { + httpResponse, errorResponse := client.DeleteOfflineCollectors(&types.DeleteOfflineCollectorsOpts{ + AliveBeforeDays: optional.NewInt32(aliveBeforeDays), + }) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) } else { - fmt.Println("collector with id " + id + " failed to delete, please try again.") + cmdutils.Output(nil, httpResponse, errorResponse, "Offline collectors have been deleted") } } } diff --git a/pkg/cmd/collectors/get/get.go b/pkg/cmd/collectors/get/get.go index 729e3efb..f6fa4648 100644 --- a/pkg/cmd/collectors/get/get.go +++ b/pkg/cmd/collectors/get/get.go @@ -1,73 +1,46 @@ package get import ( - "encoding/json" "fmt" "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "strconv" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdCollectorGet() *cobra.Command { +func NewCmdCollectorGet(client *cip.APIClient) *cobra.Command { var ( - id int + id string name string ) - cmd := &cobra.Command{ Use: "get", Short: "Gets a Sumo Logic collector information", Long: "You can use either the id or the name of the collector to specify the collector to return", Run: func(cmd *cobra.Command, args []string) { - getCollector(id, name) + getCollector(id, name, client) }, } - - cmd.Flags().IntVar(&id, "id", 0, "Specify the id of the collector") + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the collector") cmd.Flags().StringVar(&name, "name", "", "Specify the name of the collector") return cmd } -func getCollector(id int, name string) { - log := logging.GetConsoleLogger() - var collectorInfo api.CollectorResponse - requestUrl := "/v1/collectors/" - if id != 0 { - requestUrl = requestUrl + strconv.Itoa(id) +func getCollector(id string, name string, client *cip.APIClient) { + if id != "" && name != "" { + fmt.Println("Please specify and id or name, not both.") + } else if id != "" { + apiResponse, httpResponse, errorResponse := client.GetCollectorById(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } } else if name != "" { - requestUrl = requestUrl + "name/" + name - } else { - log.Fatal().Msg("please specify either a id or name of a collector") - } - - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Fatal().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Fatal().Err(err).Msg("error reading response body from request") - } - - err = json.Unmarshal(responseBody, &collectorInfo) - if err != nil { - log.Fatal().Err(err).Msg("error unmarshalling response body") - } - - collectorInfoJson, err := json.MarshalIndent(collectorInfo, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal collectorInfo") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(collectorInfoJson)) + apiResponse, httpResponse, errorResponse := client.GetCollectorByName(name) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } } } diff --git a/pkg/cmd/collectors/list/list.go b/pkg/cmd/collectors/list/list.go index f5fdfacb..ec873b40 100644 --- a/pkg/cmd/collectors/list/list.go +++ b/pkg/cmd/collectors/list/list.go @@ -1,98 +1,58 @@ package list import ( - "encoding/json" - "fmt" + "github.com/antihax/optional" "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "net/url" - "strconv" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdCollectorList() *cobra.Command { +func NewCmdCollectorList(client *cip.APIClient) *cobra.Command { var ( - filter string - limit int - offset string - offline bool - jsonFormat bool + aliveBeforeDays int32 + filter string + limit int32 + offset int32 + offline bool ) - cmd := &cobra.Command{ Use: "list", Short: "Lists Sumo Logic collectors", Run: func(cmd *cobra.Command, args []string) { - listCollectors(filter, limit, offset, offline, jsonFormat) + listCollectors(aliveBeforeDays, filter, limit, offset, offline, client) }, } - + cmd.Flags().Int32Var(&aliveBeforeDays, "aliveBeforeDays", 100, "Minimum number of days the collectors have been offline (only used when offline is set to true)") cmd.Flags().StringVar(&filter, "filter", "", "Filters the collectors returned using either installed, hosted, dead or alive") - cmd.Flags().IntVar(&limit, "limit", 1000, "Maximum number of collectors returned") - cmd.Flags().StringVar(&offset, "offset", "", "Offset into the list of collectors") + cmd.Flags().Int32Var(&limit, "limit", 1000, "Maximum number of collectors returned") + cmd.Flags().Int32Var(&offset, "offset", 0, "Offset into the list of collectors") cmd.Flags().BoolVar(&offline, "offline", false, "Lists offline collectors") - cmd.Flags().BoolVar(&jsonFormat, "jsonFormat", false, "Set to true if you want the output to be formatted JSON") return cmd } -func listCollectors(filter string, limit int, offset string, offline bool, jsonFormat bool) { - log := logging.GetConsoleLogger() - var collectorInfo api.Collectors - var requestUrl string +func listCollectors(aliveBeforeDays int32, filter string, limit int32, offset int32, offline bool, client *cip.APIClient) { if offline == true { - requestUrl = "/v1/collectors/offline" - } else { - requestUrl = "/v1/collectors" - } - - client, request := factory.NewHttpRequest("GET", requestUrl) - query := url.Values{} - if filter != "" && offline == false { - if factory.ValidateCollectorFilter(filter) == false { - log.Fatal().Msg(filter + "is an invalid field to filter by. Available fields are installed, hosted, dead or alive.") + apiResponse, httpResponse, errorResponse := client.ListOfflineCollectors(&types.ListCollectorsOfflineOpts{ + AliveBeforeDays: optional.NewInt32(aliveBeforeDays), + Limit: optional.NewInt32(limit), + Offset: optional.NewInt32(offset), + }) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) } else { - query.Add("filter", filter) + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } - } - if offset != "" && offline == false { - query.Add("offset", offset) - } - query.Add("limit", strconv.Itoa(limit)) - request.URL.RawQuery = query.Encode() - - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("error reading response body from request") - } - - jsonErr := json.Unmarshal(responseBody, &collectorInfo) - if jsonErr != nil { - log.Error().Err(jsonErr).Msg("error unmarshalling response body") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - if jsonFormat == true { - collectorInfoJson, err := json.MarshalIndent(collectorInfo.Data, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - fmt.Print(string(collectorInfoJson)) + } else if offline == false { + apiResponse, httpResponse, errorResponse := client.ListCollectors(&types.ListCollectorsOpts{ + Filter: optional.NewString(filter), + Limit: optional.NewInt32(limit), + Offset: optional.NewInt32(offset), + }) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) } else { - collectorInfoJson, err := json.Marshal(collectorInfo.Data) - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - fmt.Println(string(collectorInfoJson)) + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } } } diff --git a/pkg/cmd/collectors/update/update.go b/pkg/cmd/collectors/update/update.go index ddbf8fac..4139a360 100644 --- a/pkg/cmd/collectors/update/update.go +++ b/pkg/cmd/collectors/update/update.go @@ -1,193 +1,100 @@ package update import ( - "encoding/json" - "fmt" "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "reflect" - "strconv" - "strings" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdCollectorUpdate() *cobra.Command { +func NewCmdCollectorUpdate(client *cip.APIClient) *cobra.Command { var ( - category string - collectorId int - cutoffTimestamp int - description string - ephemeral bool - fields string - hostName string - name string - sourceSyncMode string - timeZone string - targetCPU int + category string + cutoffTimestamp int32 + description string + ephemeral bool + fieldNames []string + fieldValues []string + hostName string + id string + installedCollector bool + name string + sourceSyncMode string + timeZone string + targetCPU int32 ) - cmd := &cobra.Command{ Use: "update", Short: "updates a Sumo Logic collector settings", Run: func(cmd *cobra.Command, args []string) { - updateCollector(category, collectorId, cutoffTimestamp, description, ephemeral, fields, hostName, - name, sourceSyncMode, timeZone, targetCPU) + updateCollector(category, id, cutoffTimestamp, description, ephemeral, fieldNames, fieldValues, hostName, + installedCollector, name, sourceSyncMode, timeZone, targetCPU, client) }, } cmd.Flags().StringVar(&category, "category", "", "Specify a category for the collector") - cmd.Flags().IntVar(&collectorId, "id", 0, "Id of the collector you want to update") - cmd.Flags().IntVar(&cutoffTimestamp, "cutoffTimestamp", 0, "Specify a cutoff timestamp for the collector, specified as milliseconds since epoch") + cmd.Flags().StringVar(&id, "id", "", "Id of the collector you want to update") + cmd.Flags().Int32Var(&cutoffTimestamp, "cutoffTimestamp", 0, "Specify a cutoff timestamp for the collector, specified as milliseconds since epoch") cmd.Flags().StringVar(&description, "description", "", "Specify a description for the collector") cmd.Flags().BoolVar(&ephemeral, "ephemeral", false, "When true the collector will be deleted after 12 hours of inactivity, defaults to false") - cmd.Flags().StringVar(&fields, "fields", "", "Key value pair of fields (must be formatted as Key1:Value1,Key2:Value2)") + cmd.Flags().StringSliceVar(&fieldNames, "fieldNames", []string{}, "Specify the names of fields to add to the collector "+ + "{names need to be comma separated e.g. field1,field2") + cmd.Flags().StringSliceVar(&fieldValues, "fieldValues", []string{}, "Specify the values of fields to add to the collector "+ + "(values need to be comma separated e.g. value1,value2") cmd.Flags().StringVar(&hostName, "hostName", "", "Host name of the collector") + cmd.Flags().BoolVar(&installedCollector, "installedCollector", false, "Set to true if you are wanting to update an installed collector") cmd.Flags().StringVar(&name, "name", "", "Name of the collector, it must be unique on your account") cmd.Flags().StringVar(&sourceSyncMode, "sourceSyncMode", "", "For installed collectors whether the Collector is using local source of cloud management"+ "(\"Json\" for local source and \"UI\" for cloud source this is only configurable on installed collectors") cmd.Flags().StringVar(&timeZone, "timeZone", "", "Time zone of the Collector. Refer to the TZ column of this site: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones") - cmd.Flags().IntVar(&targetCPU, "targetCPU", 0, "When CPU utilisation exceeds this threshold, the Collector will slow down its rate of ingestion to lower its CPU utilisation"+ + cmd.Flags().Int32Var(&targetCPU, "targetCPU", 0, "When CPU utilisation exceeds this threshold, the Collector will slow down its rate of ingestion to lower its CPU utilisation"+ "(only configurable on installable collectors)") cmd.MarkFlagRequired("id") return cmd } -func updateCollector(category string, collectorId int, cutoffTimestamp int, description string, ephemeral bool, - fields string, hostName string, name string, sourceSyncMode string, timeZone string, targetCPU int) { - log := logging.GetConsoleLogger() - var collectorInfo api.CollectorResponse - - requestUrl := "/v1/collectors/" + strconv.Itoa(collectorId) - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request " + requestUrl) - } - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("error reading response body from request") - } - etag := response.Header.Values("Etag") - err = json.Unmarshal(responseBody, &collectorInfo) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - if response.StatusCode != 200 { - log.Fatal().Msg("Error code = " + strconv.Itoa(response.StatusCode) + string(responseBody)) - } - - // Building body payload to update the collector based on the differences - // between the current collector settings and the desired settings - requestBodySchema := &api.CollectorResponse{} - if collectorInfo.Collector.Category == category { - requestBodySchema.Collector.Category = collectorInfo.Collector.Category - } else { - requestBodySchema.Collector.Category = category - } - - if collectorInfo.Collector.CutoffTimestamp == cutoffTimestamp { - requestBodySchema.Collector.CutoffTimestamp = collectorInfo.Collector.CutoffTimestamp - } else { - requestBodySchema.Collector.CutoffTimestamp = cutoffTimestamp - } - - if collectorInfo.Collector.Description == description { - requestBodySchema.Collector.Description = collectorInfo.Collector.Description - } else { - requestBodySchema.Collector.Description = description - } - - if collectorInfo.Collector.Ephemeral == ephemeral { - requestBodySchema.Collector.Ephemeral = collectorInfo.Collector.Ephemeral - } else { - requestBodySchema.Collector.Ephemeral = ephemeral - } - - fieldsMap := make(map[string]string) - if fields != "" { - splitStrings := strings.Split(fields, ",") - for i, splitString := range splitStrings { - components := strings.Split(splitString, ":") - fieldsMap[components[0]] = components[1] - i++ +func updateCollector(category string, id string, cutoffTimestamp int32, description string, ephemeral bool, + fieldNames []string, fieldValues []string, hostName string, installedCollector bool, name string, sourceSyncMode string, + timeZone string, targetCPU int32, client *cip.APIClient) { + fields := cmdutils.GenerateFieldsMap(fieldNames, fieldValues) + if installedCollector == true { + apiResponse, httpResponse, errorResponse := client.UpdateInstalledCollector(types.UpdateInstalledCollectorDefinition{ + Collector: types.UpdateInstalledCollectorModel{ + Id: id, + Name: name, + Description: description, + Category: category, + CutOffTimestamp: cutoffTimestamp, + Fields: fields, + Ephemeral: ephemeral, + HostName: hostName, + SourceSyncMode: sourceSyncMode, + TimeZone: timeZone, + TargetCPU: targetCPU, + }, + }, + id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } - } - if reflect.DeepEqual(collectorInfo.Collector.Fields, fieldsMap) { - requestBodySchema.Collector.Fields = collectorInfo.Collector.Fields - } else { - requestBodySchema.Collector.Fields = fieldsMap - } - - if collectorInfo.Collector.HostName == hostName { - requestBodySchema.Collector.HostName = collectorInfo.Collector.HostName - } else { - requestBodySchema.Collector.HostName = hostName - } - - if collectorInfo.Collector.Name == name { - requestBodySchema.Collector.Name = collectorInfo.Collector.Name - } else { - requestBodySchema.Collector.Name = name - } - - if collectorInfo.Collector.CollectorType == "Installable" && collectorInfo.Collector.SourceSyncMode == sourceSyncMode { - requestBodySchema.Collector.SourceSyncMode = collectorInfo.Collector.SourceSyncMode - } else { - requestBodySchema.Collector.SourceSyncMode = sourceSyncMode - } - - if collectorInfo.Collector.TimeZone == timeZone { - requestBodySchema.Collector.TimeZone = collectorInfo.Collector.TimeZone } else { - requestBodySchema.Collector.TimeZone = timeZone - } - - if collectorInfo.Collector.CollectorType == "Installable" && collectorInfo.Collector.TargetCpu == targetCPU { - requestBodySchema.Collector.TargetCpu = collectorInfo.Collector.TargetCpu - } else { - requestBodySchema.Collector.TargetCpu = targetCPU - } - requestBodySchema.Collector.Alive = collectorInfo.Collector.Alive - requestBodySchema.Collector.CollectorType = collectorInfo.Collector.CollectorType - requestBodySchema.Collector.CollectorVersion = collectorInfo.Collector.CollectorVersion - requestBodySchema.Collector.CutoffRelativeTime = collectorInfo.Collector.CutoffRelativeTime - requestBodySchema.Collector.Links = collectorInfo.Collector.Links - requestBodySchema.Collector.Id = collectorInfo.Collector.Id - requestBodySchema.Collector.LastSeenAlive = collectorInfo.Collector.LastSeenAlive - if collectorInfo.Collector.CollectorType == "Installable" { - requestBodySchema.Collector.OsArch = collectorInfo.Collector.OsArch - requestBodySchema.Collector.OsName = collectorInfo.Collector.OsName - requestBodySchema.Collector.OsTime = collectorInfo.Collector.OsTime - requestBodySchema.Collector.OsVersion = collectorInfo.Collector.OsVersion - } - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("failed to marshal request body") - } - client, request = factory.NewHttpRequestWithBody("PUT", requestUrl, requestBody) - request.Header.Add("If-Match", etag[0]) - response, err = client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request " + requestUrl) - } - defer response.Body.Close() - responseBody, err = io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("error reading response body from request") - } - err = json.Unmarshal(responseBody, &collectorInfo) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - collectorInfoJson, err := json.MarshalIndent(&collectorInfo, "", " ") - if err != nil { - log.Error().Err(err).Msg("error marshalling response body") - } - if response.StatusCode != 200 { - log.Error().Msg("Error code = " + strconv.Itoa(response.StatusCode) + string(responseBody)) - } else { - fmt.Println(string(collectorInfoJson)) + apiResponse, httpResponse, errorResponse := client.UpdateHostedCollector(types.UpdateHostedCollectorDefinition{ + Collector: types.UpdateHostedCollectorModel{ + Id: id, + Name: name, + Description: description, + Category: category, + CutOffTimestamp: cutoffTimestamp, + Fields: fields, + TimeZone: timeZone, + }, + }, + id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } } } diff --git a/pkg/cmd/collectors/upgrade/builds/builds.go b/pkg/cmd/collectors/upgrade/builds/builds.go deleted file mode 100644 index 98c8ab9f..00000000 --- a/pkg/cmd/collectors/upgrade/builds/builds.go +++ /dev/null @@ -1,54 +0,0 @@ -package builds - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdGetBuilds() *cobra.Command { - var () - - cmd := &cobra.Command{ - Use: "builds", - Short: "Gets available Sumo Logic collector builds", - Run: func(cmd *cobra.Command, args []string) { - getBuilds() - }, - } - - return cmd -} - -func getBuilds() { - log := logging.GetConsoleLogger() - var builds api.Targets - requestUrl := "/v1/collectors/upgrades/targets" - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("error reading response body from request") - } - - err = json.Unmarshal(responseBody, &builds) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - - buildsJson, err := json.MarshalIndent(builds, "", " ") - - if response.StatusCode == 200 { - fmt.Println(string(buildsJson)) - } else { - factory.HttpError(response.StatusCode, responseBody, log) - } -} diff --git a/pkg/cmd/collectors/upgrade/get/get.go b/pkg/cmd/collectors/upgrade/get/get.go deleted file mode 100644 index 04027c73..00000000 --- a/pkg/cmd/collectors/upgrade/get/get.go +++ /dev/null @@ -1,69 +0,0 @@ -package get - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "net/url" - "strconv" -) - -func NewCmdGetUpgradableCollectors() *cobra.Command { - var ( - toVersion string - offset int - limit int - ) - - cmd := &cobra.Command{ - Use: "get", - Short: "Gets collectors in Sumo Logic that are upgradable", - Run: func(cmd *cobra.Command, args []string) { - getUpgradableCollectors(toVersion, offset, limit) - }, - } - - cmd.Flags().StringVar(&toVersion, "version", "", "Collector build to upgrade to, if not specified defaults to the latest version") - cmd.Flags().IntVar(&offset, "offset", 0, "Offset into the list of collectors") - cmd.Flags().IntVar(&limit, "limit", 50, "Maximum number of collectors to return") - return cmd -} - -func getUpgradableCollectors(toVersion string, offset int, limit int) { - log := logging.GetConsoleLogger() - var collectorInfo api.Collectors - requestUrl := "/v1/collectors/upgrades/collectors" - client, request := factory.NewHttpRequest("GET", requestUrl) - query := url.Values{} - query.Add("toVersion", toVersion) - query.Add("offset", strconv.Itoa(offset)) - query.Add("limit", strconv.Itoa(limit)) - request.URL.RawQuery = query.Encode() - - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("error reading response body from request") - } - - err = json.Unmarshal(responseBody, &collectorInfo) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - - collectorInfoJson, err := json.MarshalIndent(collectorInfo.Data, "", " ") - - if response.StatusCode == 200 { - fmt.Println(string(collectorInfoJson)) - } else { - factory.HttpError(response.StatusCode, responseBody, log) - } -} diff --git a/pkg/cmd/collectors/upgrade/get_available_builds/get_available_builds.go b/pkg/cmd/collectors/upgrade/get_available_builds/get_available_builds.go new file mode 100644 index 00000000..f87948c4 --- /dev/null +++ b/pkg/cmd/collectors/upgrade/get_available_builds/get_available_builds.go @@ -0,0 +1,27 @@ +package get_available_builds + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdGetBuilds(client *cip.APIClient) *cobra.Command { + cmd := &cobra.Command{ + Use: "get-available-builds", + Short: "Gets available Sumo Logic collector builds", + Run: func(cmd *cobra.Command, args []string) { + getBuilds(client) + }, + } + return cmd +} + +func getBuilds(client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.GetAvailableBuilds() + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/collectors/upgrade/get_upgradable_collectors/get_upgradable_collectors.go b/pkg/cmd/collectors/upgrade/get_upgradable_collectors/get_upgradable_collectors.go new file mode 100644 index 00000000..c8ec66f2 --- /dev/null +++ b/pkg/cmd/collectors/upgrade/get_upgradable_collectors/get_upgradable_collectors.go @@ -0,0 +1,41 @@ +package get_upgradable_collectors + +import ( + "github.com/antihax/optional" + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdGetUpgradableCollectors(client *cip.APIClient) *cobra.Command { + var ( + toVersion string + offset int32 + limit int32 + ) + cmd := &cobra.Command{ + Use: "get-upgradable-collectors", + Short: "Gets collectors in Sumo Logic that are upgradable", + Run: func(cmd *cobra.Command, args []string) { + getUpgradableCollectors(toVersion, offset, limit, client) + }, + } + cmd.Flags().StringVar(&toVersion, "version", "", "Collector build to upgrade to, if not specified defaults to the latest version") + cmd.Flags().Int32Var(&offset, "offset", 0, "Offset into the list of collectors") + cmd.Flags().Int32Var(&limit, "limit", 50, "Maximum number of collectors to return") + return cmd +} + +func getUpgradableCollectors(toVersion string, offset int32, limit int32, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.GetUpgradableCollectors(&types.GetUpgradableCollectorsOpts{ + Limit: optional.NewInt32(limit), + Offset: optional.NewInt32(offset), + ToVersion: optional.NewString(toVersion), + }) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/collectors/upgrade/start/start.go b/pkg/cmd/collectors/upgrade/start/start.go index cbb87df3..11b73604 100644 --- a/pkg/cmd/collectors/upgrade/start/start.go +++ b/pkg/cmd/collectors/upgrade/start/start.go @@ -1,69 +1,44 @@ package start import ( - "encoding/json" "fmt" "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "strings" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" + "strconv" ) -func NewCmdUpgradeStart() *cobra.Command { +func NewCmdUpgradeStart(client *cip.APIClient) *cobra.Command { var ( - collectorId int - toVersion string + id string + toVersion string ) - cmd := &cobra.Command{ Use: "start", Short: "Starts an upgrade or downgrade of an existing installed collector", Run: func(cmd *cobra.Command, args []string) { - upgradeStart(collectorId, toVersion) + upgradeStart(id, toVersion, client) }, } - - cmd.Flags().IntVar(&collectorId, "collectorId", 0, "Id of the collector to upgrade") + cmd.Flags().StringVar(&id, "id", "", "Id of the collector to upgrade") cmd.Flags().StringVar(&toVersion, "version", "", "Version to upgrade or downgrade the collector to") cmd.MarkFlagRequired("collectorId") return cmd } -func upgradeStart(collectorId int, toVersion string) { - log := logging.GetConsoleLogger() - var upgradeInfo api.UpgradeTaskResponse - requestBodySchema := &api.UpgradeTask{ - CollectorId: collectorId, - ToVersion: toVersion, - } - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("failed to marshal response body") - } - - requestUrl := "/v1/collectors/upgrades" - client, request := factory.NewHttpRequestWithBody("POST", requestUrl, requestBody) - response, err := client.Do(request) +func upgradeStart(id string, toVersion string, client *cip.APIClient) { + idInt, err := strconv.Atoi(id) if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) + fmt.Println("failed to convert string to int") } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("error reading response body from request") - } - - err = json.Unmarshal(responseBody, &upgradeInfo) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - if response.StatusCode == 202 { - id := strings.Split(upgradeInfo.Link.Href, "v1/collectors/upgrades/") - fmt.Println(id[1]) - } else if response.StatusCode == 400 { - log.Error().Msg("Bad request please try again") + apiResponse, httpResponse, errorResponse := client.CreateUpgradeOrDowngradeTask(types.CreateUpgradeOrDowngradeRequest{ + CollectorId: idInt, + ToVersion: toVersion, + }) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } } diff --git a/pkg/cmd/collectors/upgrade/status/status.go b/pkg/cmd/collectors/upgrade/status/status.go index ff7da506..67544c55 100644 --- a/pkg/cmd/collectors/upgrade/status/status.go +++ b/pkg/cmd/collectors/upgrade/status/status.go @@ -1,20 +1,13 @@ package status import ( - "encoding/json" - "fmt" "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "net/url" - "strconv" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdUpgradableCollectorStatus() *cobra.Command { - var upgradeTaskId int - +func NewCmdUpgradableCollectorStatus(client *cip.APIClient) *cobra.Command { + var upgradeTaskId string cmd := &cobra.Command{ Use: "status", Long: `Gets the status of a collector upgrade or downgrade. @@ -25,45 +18,19 @@ The status of the upgrade can be one of the following 3 - failed 6 - progressing, the upgrade is running on the Collector`, Run: func(cmd *cobra.Command, args []string) { - upgradableCollectorStatus(upgradeTaskId) + upgradableCollectorStatus(upgradeTaskId, client) }, } - cmd.Flags().IntVar(&upgradeTaskId, "upgradeTaskId", 0, "Id to the upgrade task") + cmd.Flags().StringVar(&upgradeTaskId, "upgradeTaskId", "", "Id to the upgrade task") cmd.MarkFlagRequired("upgradeTaskId") return cmd } -func upgradableCollectorStatus(upgradeTaskId int) { - log := logging.GetConsoleLogger() - var status api.UpgradeTaskStatus - requestUrl := "/v1/collectors/upgrades/" + strconv.Itoa(upgradeTaskId) - client, request := factory.NewHttpRequest("GET", requestUrl) - query := url.Values{} - query.Add("upgradeTaskId", strconv.Itoa(upgradeTaskId)) - request.URL.RawQuery = query.Encode() - - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) +func upgradableCollectorStatus(upgradeTaskId string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.GetUpgradeOrDowngradeTaskStatus(upgradeTaskId) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("error reading body from request") - } - - err = json.Unmarshal(responseBody, &status) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - if response.StatusCode == 200 { - statusJson, err := json.MarshalIndent(status, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal status") - } - fmt.Println(string(statusJson)) - } else if response.StatusCode == 404 { - fmt.Println("The upgrade task Id was not found") - } - } diff --git a/pkg/cmd/collectors/upgrade/upgrade.go b/pkg/cmd/collectors/upgrade/upgrade.go index ec272f04..118a6b87 100644 --- a/pkg/cmd/collectors/upgrade/upgrade.go +++ b/pkg/cmd/collectors/upgrade/upgrade.go @@ -2,21 +2,22 @@ package upgrade import ( "github.com/spf13/cobra" - cmdCollectorUpgradeBuilds "github.com/wizedkyle/sumocli/pkg/cmd/collectors/upgrade/builds" - cmdCollectorUpgradeGet "github.com/wizedkyle/sumocli/pkg/cmd/collectors/upgrade/get" - cmdCollectorStart "github.com/wizedkyle/sumocli/pkg/cmd/collectors/upgrade/start" + cmdCollectorUpgradeBuilds "github.com/wizedkyle/sumocli/pkg/cmd/collectors/upgrade/get_available_builds" + cmdCollectorUpgradeGet "github.com/wizedkyle/sumocli/pkg/cmd/collectors/upgrade/get_upgradable_collectors" + cmdCollectorUpgradeStart "github.com/wizedkyle/sumocli/pkg/cmd/collectors/upgrade/start" cmdCollectorStatus "github.com/wizedkyle/sumocli/pkg/cmd/collectors/upgrade/status" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdUpgradeCollectors() *cobra.Command { +func NewCmdUpgradeCollectors(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "upgrade", Short: "Manages the upgrading of collectors", } - cmd.AddCommand(cmdCollectorUpgradeBuilds.NewCmdGetBuilds()) - cmd.AddCommand(cmdCollectorUpgradeGet.NewCmdGetUpgradableCollectors()) - cmd.AddCommand(cmdCollectorStart.NewCmdUpgradeStart()) - cmd.AddCommand(cmdCollectorStatus.NewCmdUpgradableCollectorStatus()) + cmd.AddCommand(cmdCollectorUpgradeBuilds.NewCmdGetBuilds(client)) + cmd.AddCommand(cmdCollectorUpgradeGet.NewCmdGetUpgradableCollectors(client)) + cmd.AddCommand(cmdCollectorUpgradeStart.NewCmdUpgradeStart(client)) + cmd.AddCommand(cmdCollectorStatus.NewCmdUpgradableCollectorStatus(client)) return cmd } diff --git a/pkg/cmd/login/login.go b/pkg/cmd/configure/configure.go similarity index 98% rename from pkg/cmd/login/login.go rename to pkg/cmd/configure/configure.go index 6b7e22a2..75aa22dc 100644 --- a/pkg/cmd/login/login.go +++ b/pkg/cmd/configure/configure.go @@ -1,4 +1,4 @@ -package login +package configure import ( "encoding/json" @@ -14,11 +14,11 @@ import ( "strings" ) -func NewCmdLogin() *cobra.Command { +func NewCmdConfigure() *cobra.Command { var showAccessId bool cmd := &cobra.Command{ - Use: "login", + Use: "configure", Short: "Sets Sumo Logic credentials", Long: "Interactively sets the Sumo Logic Access Id, Access Key and API endpoint.", Run: func(cmd *cobra.Command, args []string) { diff --git a/pkg/cmd/content/content.go b/pkg/cmd/content/content.go index cc4e4fb0..f00d4981 100644 --- a/pkg/cmd/content/content.go +++ b/pkg/cmd/content/content.go @@ -2,37 +2,36 @@ package content import ( "github.com/spf13/cobra" - cmdContentCopyStatus "github.com/wizedkyle/sumocli/pkg/cmd/content/copy-status" - cmdContentDeletionStatus "github.com/wizedkyle/sumocli/pkg/cmd/content/deletion-status" - cmdContentExportResult "github.com/wizedkyle/sumocli/pkg/cmd/content/export-result" - cmdContentExportStatus "github.com/wizedkyle/sumocli/pkg/cmd/content/export-status" cmdContentGet "github.com/wizedkyle/sumocli/pkg/cmd/content/get" - cmdContentGetPath "github.com/wizedkyle/sumocli/pkg/cmd/content/get-path" - cmdContentImportStatus "github.com/wizedkyle/sumocli/pkg/cmd/content/import-status" + cmdContentCopyStatus "github.com/wizedkyle/sumocli/pkg/cmd/content/get_copy_status" + cmdContentDeletionStatus "github.com/wizedkyle/sumocli/pkg/cmd/content/get_deletion_status" + cmdContentExportResult "github.com/wizedkyle/sumocli/pkg/cmd/content/get_export_result" + cmdContentExportStatus "github.com/wizedkyle/sumocli/pkg/cmd/content/get_export_status" + cmdContentImportStatus "github.com/wizedkyle/sumocli/pkg/cmd/content/get_import_status" cmdContentMove "github.com/wizedkyle/sumocli/pkg/cmd/content/move" - cmdContentStartCopy "github.com/wizedkyle/sumocli/pkg/cmd/content/start-copy" - cmdContentStartDeletion "github.com/wizedkyle/sumocli/pkg/cmd/content/start-deletion" - cmdContentStartExport "github.com/wizedkyle/sumocli/pkg/cmd/content/start-export" - cmdContentStartImport "github.com/wizedkyle/sumocli/pkg/cmd/content/start-import" + cmdContentStartCopy "github.com/wizedkyle/sumocli/pkg/cmd/content/start_copy" + cmdContentStartDeletion "github.com/wizedkyle/sumocli/pkg/cmd/content/start_deletion" + cmdContentStartExport "github.com/wizedkyle/sumocli/pkg/cmd/content/start_export" + cmdContentStartImport "github.com/wizedkyle/sumocli/pkg/cmd/content/start_import" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdContent() *cobra.Command { +func NewCmdContent(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "content ", Short: "Manage content", Long: "Commands that allow you to manage content in your Sumo Logic tenant", } - cmd.AddCommand(cmdContentCopyStatus.NewCmdCopyStatus()) - cmd.AddCommand(cmdContentDeletionStatus.NewCmdDeletionStatus()) - cmd.AddCommand(cmdContentExportResult.NewCmdExportResult()) - cmd.AddCommand(cmdContentExportStatus.NewCmdExportStatus()) - cmd.AddCommand(cmdContentGet.NewCmdGet()) - cmd.AddCommand(cmdContentGetPath.NewCmdGetPath()) - cmd.AddCommand(cmdContentImportStatus.NewCmdImportStatus()) - cmd.AddCommand(cmdContentMove.NewCmdMove()) - cmd.AddCommand(cmdContentStartDeletion.NewCmdStartDeletion()) - cmd.AddCommand(cmdContentStartCopy.NewCmdStartCopy()) - cmd.AddCommand(cmdContentStartExport.NewCmdStartExport()) - cmd.AddCommand(cmdContentStartImport.NewCmdStartImport()) + cmd.AddCommand(cmdContentCopyStatus.NewCmdGetCopyStatus(client)) + cmd.AddCommand(cmdContentDeletionStatus.NewCmdGetDeletionStatus(client)) + cmd.AddCommand(cmdContentExportResult.NewCmdGetExportResult(client)) + cmd.AddCommand(cmdContentExportStatus.NewCmdExportStatus(client)) + cmd.AddCommand(cmdContentGet.NewCmdGet(client)) + cmd.AddCommand(cmdContentImportStatus.NewCmdGetImportStatus(client)) + cmd.AddCommand(cmdContentMove.NewCmdMove(client)) + cmd.AddCommand(cmdContentStartDeletion.NewCmdStartDeletion(client)) + cmd.AddCommand(cmdContentStartCopy.NewCmdStartCopy(client)) + cmd.AddCommand(cmdContentStartExport.NewCmdStartExport(client)) + cmd.AddCommand(cmdContentStartImport.NewCmdStartImport(client)) return cmd } diff --git a/pkg/cmd/content/copy-status/copy-status.go b/pkg/cmd/content/copy-status/copy-status.go deleted file mode 100644 index 19d6851b..00000000 --- a/pkg/cmd/content/copy-status/copy-status.go +++ /dev/null @@ -1,69 +0,0 @@ -package copy_status - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdCopyStatus() *cobra.Command { - var ( - id string - jobId string - isAdminMode bool - ) - - cmd := &cobra.Command{ - Use: "copy-status", - Short: "Get the status of the copy request with the given job identifier. On success, field statusMessage will contain identifier of the newly copied content.", - Run: func(cmd *cobra.Command, args []string) { - copyStatus(id, jobId, isAdminMode) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the content that was copied") - cmd.Flags().StringVar(&jobId, "jobId", "", "Specify the job id for the copy (returned from running sumocli content start-copy)") - cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "Set to true if you want to perform the request as a content administrator") - cmd.MarkFlagRequired("id") - cmd.MarkFlagRequired("jobId") - return cmd -} - -func copyStatus(id string, jobId string, isAdminMode bool) { - var copyStatusResponse api.ExportStatusResponse - log := logging.GetConsoleLogger() - requestUrl := "/v2/content/" + id + "/copy/" + jobId + "/status" - client, request := factory.NewHttpRequest("GET", requestUrl) - if isAdminMode == true { - request.Header.Add("isAdminMode", "true") - } - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, ©StatusResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - copyStatusJson, err := json.MarshalIndent(copyStatusResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal exportStatusResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(copyStatusJson)) - } -} diff --git a/pkg/cmd/content/deletion-status/deletion-status.go b/pkg/cmd/content/deletion-status/deletion-status.go deleted file mode 100644 index 87c4e139..00000000 --- a/pkg/cmd/content/deletion-status/deletion-status.go +++ /dev/null @@ -1,69 +0,0 @@ -package deletion_status - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdDeletionStatus() *cobra.Command { - var ( - id string - jobId string - isAdminMode bool - ) - - cmd := &cobra.Command{ - Use: "deletion-status", - Short: "Get the status of an asynchronous content deletion job request for the given job identifier.", - Run: func(cmd *cobra.Command, args []string) { - deletionStatus(id, jobId, isAdminMode) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the content to delete") - cmd.Flags().StringVar(&jobId, "jobId", "", "Specify the job id for the deletion (returned from running sumocli content start-deletion)") - cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "Set to true if you want to perform the request as a content administrator") - cmd.MarkFlagRequired("contentId") - cmd.MarkFlagRequired("jobId") - return cmd -} - -func deletionStatus(id string, jobId string, isAdminMode bool) { - var deletionStatusResponse api.ExportStatusResponse - log := logging.GetConsoleLogger() - requestUrl := "/v2/content/" + id + "/delete/" + jobId + "/status" - client, request := factory.NewHttpRequest("GET", requestUrl) - if isAdminMode == true { - request.Header.Add("isAdminMode", "true") - } - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &deletionStatusResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - importStatusJson, err := json.MarshalIndent(deletionStatusResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal exportStatusResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(importStatusJson)) - } -} diff --git a/pkg/cmd/content/export-result/export-result.go b/pkg/cmd/content/export-result/export-result.go deleted file mode 100644 index 6c41645a..00000000 --- a/pkg/cmd/content/export-result/export-result.go +++ /dev/null @@ -1,178 +0,0 @@ -package export_result - -import ( - "encoding/json" - "fmt" - "github.com/rs/zerolog/log" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "os" - "path/filepath" -) - -func NewCmdExportResult() *cobra.Command { - var ( - contentId string - jobId string - isAdminMode bool - saveToFile bool - filePath string - fileName string - ) - - cmd := &cobra.Command{ - Use: "export-result", - Short: "Gets results from content export job for the given job identifier", - Run: func(cmd *cobra.Command, args []string) { - exportResult(contentId, jobId, isAdminMode, saveToFile, filePath, fileName) - }, - } - cmd.Flags().StringVar(&contentId, "contentId", "", "Specify the id of the content item to export") - cmd.Flags().StringVar(&jobId, "jobId", "", "Specify the job id for the export (returned from running sumocli content start-export)") - cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "Set to true if you want to perform the request as a content administrator") - cmd.Flags().BoolVar(&saveToFile, "saveToFile", false, "Saves the export results to a file") - cmd.Flags().StringVar(&filePath, "filePath", "", "Folder path to save results to. If this is empty then the results will be saved to the users home directory") - cmd.Flags().StringVar(&fileName, "fileName", "", "File name for the results.") - cmd.MarkFlagRequired("contentId") - cmd.MarkFlagRequired("jobId") - return cmd -} - -func exportResult(contentId string, jobId string, isAdminMode bool, saveToFile bool, filePath string, fileName string) { - var responseType api.ResponseType - log := logging.GetConsoleLogger() - requestUrl := "/v2/content/" + contentId + "/export/" + jobId + "/result" - client, request := factory.NewHttpRequest("GET", requestUrl) - if isAdminMode == true { - request.Header.Add("isAdminMode", "true") - } - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &responseType) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - if responseType.Type == "FolderSyncDefinition" { - var folderSyncResponse api.FolderSyncDefinition - err = json.Unmarshal(responseBody, &folderSyncResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body into DashboardSyncDefinition") - } - folderSyncResponseJson, err := json.MarshalIndent(folderSyncResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal dashboardSyncResponse") - } - writeResults(folderSyncResponseJson, saveToFile, filePath, fileName) - } else if responseType.Type == "DashboardSyncDefinition" { - var dashboardSyncResponse api.DashboardSyncDefinition - err = json.Unmarshal(responseBody, &dashboardSyncResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body into DashboardSyncDefinition") - } - dashboardSyncResponseJson, err := json.MarshalIndent(dashboardSyncResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal dashboardSyncResponse") - } - writeResults(dashboardSyncResponseJson, saveToFile, filePath, fileName) - } else if responseType.Type == "MewboardSyncDefinition" { - var mewboardSyncResponse api.MewboardSyncDefinition - err = json.Unmarshal(responseBody, &mewboardSyncResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body into DashboardSyncDefinition") - } - mewboardSyncResponseJson, err := json.MarshalIndent(mewboardSyncResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal dashboardSyncResponse") - } - writeResults(mewboardSyncResponseJson, saveToFile, filePath, fileName) - } else if responseType.Type == "SavedSearchWithScheduleSyncDefinition" { - var savedSearchWithScheduleSyncResponse api.SavedSearchWithScheduleSyncDefinition - err = json.Unmarshal(responseBody, &savedSearchWithScheduleSyncResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body into DashboardSyncDefinition") - } - savedSearchWithScheduleSyncResponseJson, err := json.MarshalIndent(savedSearchWithScheduleSyncResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal dashboardSyncResponse") - } - writeResults(savedSearchWithScheduleSyncResponseJson, saveToFile, filePath, fileName) - } else if responseType.Type == "MetricsSavedSearchSyncDefinition" { - var metricsSavedSearchSyncResponse api.MetricsSavedSearchSyncDefinition - err = json.Unmarshal(responseBody, &metricsSavedSearchSyncResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body into DashboardSyncDefinition") - } - metricsSavedSearchSyncResponseJson, err := json.MarshalIndent(metricsSavedSearchSyncResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal dashboardSyncResponse") - } - writeResults(metricsSavedSearchSyncResponseJson, saveToFile, filePath, fileName) - } else if responseType.Type == "MetricsSearchSyncDefinition" { - var metricsSearchSyncResponse api.MetricsSearchSyncDefinition - err = json.Unmarshal(responseBody, &metricsSearchSyncResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body into DashboardSyncDefinition") - } - metricsSearchSyncResponseJson, err := json.MarshalIndent(metricsSearchSyncResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal dashboardSyncResponse") - } - writeResults(metricsSearchSyncResponseJson, saveToFile, filePath, fileName) - } else if responseType.Type == "LookupTableSyncDefinition" { - var lookupTableSyncResponse api.LookupTableSyncDefinition - err = json.Unmarshal(responseBody, &lookupTableSyncResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body into DashboardSyncDefinition") - } - lookupTableSyncResponseJson, err := json.MarshalIndent(lookupTableSyncResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal dashboardSyncResponse") - } - writeResults(lookupTableSyncResponseJson, saveToFile, filePath, fileName) - } -} - -func writeResults(resultsData []byte, saveToFile bool, filePath string, fileName string) { - if saveToFile == true { - if filePath != "" { - if _, err := os.Stat(filePath); os.IsNotExist(err) { - err := os.MkdirAll(filePath, 0755) - if err != nil { - log.Fatal().Err(err).Msg("failed to create file path") - } - } - resultFile := filepath.Join(filePath, fileName) - err := os.WriteFile(resultFile, resultsData, 0644) - if err != nil { - log.Error().Err(err).Msg("failed to write results file " + filePath) - } - fmt.Println("Results written to " + resultFile) - } else { - homeDirectory, err := os.UserHomeDir() - if err != nil { - log.Error().Err(err).Msg("failed to get user home directory") - } - resultFile := filepath.Join(homeDirectory, "results.json") - err = os.WriteFile(resultFile, resultsData, 0644) - if err != nil { - log.Error().Err(err).Msg("failed to write results file " + resultFile) - } - fmt.Println("Results written to " + resultFile) - } - } else { - fmt.Println(string(resultsData)) - } -} diff --git a/pkg/cmd/content/export-status/export-status.go b/pkg/cmd/content/export-status/export-status.go deleted file mode 100644 index 7d7def50..00000000 --- a/pkg/cmd/content/export-status/export-status.go +++ /dev/null @@ -1,69 +0,0 @@ -package export_status - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdExportStatus() *cobra.Command { - var ( - contentId string - jobId string - isAdminMode bool - ) - - cmd := &cobra.Command{ - Use: "export-status", - Short: "Get the status of an asynchronous content export request for the given job identifier", - Run: func(cmd *cobra.Command, args []string) { - exportStatus(contentId, jobId, isAdminMode) - }, - } - cmd.Flags().StringVar(&contentId, "contentId", "", "Specify the id of the content item to export") - cmd.Flags().StringVar(&jobId, "jobId", "", "Specify the job id for the export (returned from running sumocli content start-export)") - cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "Set to true if you want to perform the request as a content administrator") - cmd.MarkFlagRequired("contentId") - cmd.MarkFlagRequired("jobId") - return cmd -} - -func exportStatus(contentId string, jobId string, isAdminMode bool) { - var exportStatusResponse api.ExportStatusResponse - log := logging.GetConsoleLogger() - requestUrl := "/v2/content/" + contentId + "/export/" + jobId + "/status" - client, request := factory.NewHttpRequest("GET", requestUrl) - if isAdminMode == true { - request.Header.Add("isAdminMode", "true") - } - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &exportStatusResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - exportStatusJson, err := json.MarshalIndent(exportStatusResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal exportStatusResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(exportStatusJson)) - } -} diff --git a/pkg/cmd/content/get-path/get-path.go b/pkg/cmd/content/get-path/get-path.go deleted file mode 100644 index a7077bb1..00000000 --- a/pkg/cmd/content/get-path/get-path.go +++ /dev/null @@ -1,59 +0,0 @@ -package get_path - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdGetPath() *cobra.Command { - var id string - - cmd := &cobra.Command{ - Use: "get-path", - Short: "Gets the full path of a content item with the given identifier", - Run: func(cmd *cobra.Command, args []string) { - getPath(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the content") - cmd.MarkFlagRequired("id") - return cmd -} - -func getPath(id string) { - var pathResponse api.GetPathResponse - log := logging.GetConsoleLogger() - requestUrl := "/v2/content/" + id + "/path" - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &pathResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - pathJson, err := json.MarshalIndent(pathResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal pathResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(pathJson)) - } -} diff --git a/pkg/cmd/content/get/get.go b/pkg/cmd/content/get/get.go index 9b905521..55a2d0f4 100644 --- a/pkg/cmd/content/get/get.go +++ b/pkg/cmd/content/get/get.go @@ -1,63 +1,45 @@ package get import ( - "encoding/json" "fmt" "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "net/url" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdGet() *cobra.Command { - var path string - +func NewCmdGet(client *cip.APIClient) *cobra.Command { + var ( + contentId string + path string + ) cmd := &cobra.Command{ Use: "get", - Short: "Gets a content item corresponding to the provided path", + Short: "Gets a content item corresponding to the provided path or via the identifier of the content.", Run: func(cmd *cobra.Command, args []string) { - getContent(path) + getContent(contentId, path, client) }, } + cmd.Flags().StringVar(&contentId, "contentId", "", "Specify the id of the content") cmd.Flags().StringVar(&path, "path", "", "Specify the path of the content you want to retrieve (e.g. /Library/Users/user@demo.com/SampleFolder)") - cmd.MarkFlagRequired("path") return cmd } -func getContent(path string) { - var contentResponse api.GetContentResponse - log := logging.GetConsoleLogger() - requestUrl := "/v2/content/path" - client, request := factory.NewHttpRequest("GET", requestUrl) - query := url.Values{} - query.Add("path", path) - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &contentResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - contentJson, err := json.MarshalIndent(contentResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal contentResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(contentJson)) +func getContent(contentId string, path string, client *cip.APIClient) { + if contentId != "" { + apiResponse, httpResponse, errorResponse := client.GetPathById(contentId) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + } else if path != "" { + apiResponse, httpResponse, errorResponse := client.GetItemByPath(path) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + } else if contentId != "" && path != "" { + fmt.Println("Please specify only contentId or path.") } } diff --git a/pkg/cmd/content/get_copy_status/get_copy_status.go b/pkg/cmd/content/get_copy_status/get_copy_status.go new file mode 100644 index 00000000..c97db3bc --- /dev/null +++ b/pkg/cmd/content/get_copy_status/get_copy_status.go @@ -0,0 +1,45 @@ +package get_copy_status + +import ( + "github.com/antihax/optional" + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdGetCopyStatus(client *cip.APIClient) *cobra.Command { + var ( + id string + jobId string + isAdminMode bool + ) + cmd := &cobra.Command{ + Use: "get-copy-status", + Short: "Get the status of the copy request with the given job identifier. On success, field statusMessage will contain identifier of the newly copied content.", + Run: func(cmd *cobra.Command, args []string) { + copyStatus(id, jobId, isAdminMode, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the content that was copied") + cmd.Flags().StringVar(&jobId, "jobId", "", "Specify the job id for the copy (returned from running sumocli content start-copy)") + cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "Set to true if you want to perform the request as a content administrator") + cmd.MarkFlagRequired("id") + cmd.MarkFlagRequired("jobId") + return cmd +} + +func copyStatus(id string, jobId string, isAdminMode bool, client *cip.APIClient) { + var options types.ContentOpts + if isAdminMode == true { + options.IsAdminMode = optional.NewString("true") + } else { + options.IsAdminMode = optional.NewString("false") + } + apiResponse, httpResponse, errorResponse := client.AsyncCopyStatus(id, jobId, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/content/get_deletion_status/get_deletion_status.go b/pkg/cmd/content/get_deletion_status/get_deletion_status.go new file mode 100644 index 00000000..edeced87 --- /dev/null +++ b/pkg/cmd/content/get_deletion_status/get_deletion_status.go @@ -0,0 +1,45 @@ +package get_deletion_status + +import ( + "github.com/antihax/optional" + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdGetDeletionStatus(client *cip.APIClient) *cobra.Command { + var ( + id string + jobId string + isAdminMode bool + ) + cmd := &cobra.Command{ + Use: "get-deletion-status", + Short: "Get the status of an asynchronous content deletion job request for the given job identifier.", + Run: func(cmd *cobra.Command, args []string) { + deletionStatus(id, jobId, isAdminMode, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the content to delete") + cmd.Flags().StringVar(&jobId, "jobId", "", "Specify the job id for the deletion (returned from running sumocli content start-deletion)") + cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "Set to true if you want to perform the request as a content administrator") + cmd.MarkFlagRequired("contentId") + cmd.MarkFlagRequired("jobId") + return cmd +} + +func deletionStatus(id string, jobId string, isAdminMode bool, client *cip.APIClient) { + var options types.ContentOpts + if isAdminMode == true { + options.IsAdminMode = optional.NewString("true") + } else { + options.IsAdminMode = optional.NewString("false") + } + apiResponse, httpResponse, errorResponse := client.GetAsyncDeleteStatus(id, jobId, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/content/get_export_result/get_export_result.go b/pkg/cmd/content/get_export_result/get_export_result.go new file mode 100644 index 00000000..7fa65d20 --- /dev/null +++ b/pkg/cmd/content/get_export_result/get_export_result.go @@ -0,0 +1,144 @@ +package get_export_result + +import ( + "encoding/json" + "fmt" + "github.com/antihax/optional" + "github.com/rs/zerolog/log" + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" + "net/http" + "os" + "path/filepath" +) + +func NewCmdGetExportResult(client *cip.APIClient) *cobra.Command { + var ( + contentId string + jobId string + isAdminMode bool + saveToFile bool + filePath string + fileName string + ) + cmd := &cobra.Command{ + Use: "get-export-result", + Short: "Gets results from content export job for the given job identifier", + Run: func(cmd *cobra.Command, args []string) { + exportResult(contentId, jobId, isAdminMode, saveToFile, filePath, fileName, client) + }, + } + cmd.Flags().StringVar(&contentId, "contentId", "", "Specify the id of the content item to export") + cmd.Flags().StringVar(&jobId, "jobId", "", "Specify the job id for the export (returned from running sumocli content start-export)") + cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "Set to true if you want to perform the request as a content administrator") + cmd.Flags().BoolVar(&saveToFile, "saveToFile", false, "Saves the export results to a file") + cmd.Flags().StringVar(&filePath, "filePath", "", "Folder path to save results to. If this is empty then the results will be saved to the users home directory") + cmd.Flags().StringVar(&fileName, "fileName", "", "File name for the results.") + cmd.MarkFlagRequired("contentId") + cmd.MarkFlagRequired("jobId") + return cmd +} + +func exportResult(contentId string, jobId string, isAdminMode bool, saveToFile bool, filePath string, fileName string, + client *cip.APIClient) { + var options types.ContentOpts + if isAdminMode == true { + options.IsAdminMode = optional.NewString("true") + } else { + options.IsAdminMode = optional.NewString("false") + } + apiResponse, httpResponse, errorResponse := client.GetAsyncExportResult(contentId, jobId, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + if apiResponse.Type_ == "FolderSyncDefinition" { + results, httpResponse, errorResponse := client.GetFolderAsyncExportResult(contentId, jobId, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + outputResults(saveToFile, filePath, fileName, results, httpResponse, errorResponse) + } + } else if apiResponse.Type_ == "DashboardSyncDefinition" { + results, httpResponse, errorResponse := client.GetDashboardAsyncExportResult(contentId, jobId, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + outputResults(saveToFile, filePath, fileName, results, httpResponse, errorResponse) + } + } else if apiResponse.Type_ == "MewboardSyncDefinition" { + results, httpResponse, errorResponse := client.GetMewboardAsyncExportResult(contentId, jobId, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + outputResults(saveToFile, filePath, fileName, results, httpResponse, errorResponse) + } + } else if apiResponse.Type_ == "SavedSearchWithScheduleSyncDefinition" { + results, httpResponse, errorResponse := client.GetSavedSearchAsyncExportResult(contentId, jobId, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + outputResults(saveToFile, filePath, fileName, results, httpResponse, errorResponse) + } + } else if apiResponse.Type_ == "MetricsSavedSearchSyncDefinition" { + results, httpResponse, errorResponse := client.GetMetricsSearchAsyncExportResult(contentId, jobId, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + outputResults(saveToFile, filePath, fileName, results, httpResponse, errorResponse) + } + } else if apiResponse.Type_ == "MetricsSearchSyncDefinition" { + results, httpResponse, errorResponse := client.GetMetricsSearchAsyncExportResult(contentId, jobId, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + outputResults(saveToFile, filePath, fileName, results, httpResponse, errorResponse) + } + } else if apiResponse.Type_ == "LookupTableSyncDefinition" { + results, httpResponse, errorResponse := client.GetLookupTableAsyncExportResult(contentId, jobId, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + outputResults(saveToFile, filePath, fileName, results, httpResponse, errorResponse) + } + } + } +} + +func outputResults(saveToFile bool, filePath string, fileName string, apiResponse interface{}, + httpResponse *http.Response, errorResponse error) { + if saveToFile == true { + apiResponseBytes, err := json.Marshal(apiResponse) + if err != nil { + log.Fatal().Err(err).Msg("failed to convert apiResponse to byte array") + } + if filePath != "" { + if _, err := os.Stat(filePath); os.IsNotExist(err) { + err := os.MkdirAll(filePath, 0755) + if err != nil { + log.Fatal().Err(err).Msg("failed to create file path") + } + } + resultFile := filepath.Join(filePath, fileName) + err := os.WriteFile(resultFile, apiResponseBytes, 0644) + if err != nil { + log.Error().Err(err).Msg("failed to write results file " + filePath) + } + fmt.Println("Results written to " + resultFile) + } else { + homeDirectory, err := os.UserHomeDir() + if err != nil { + log.Error().Err(err).Msg("failed to get user home directory") + } + resultFile := filepath.Join(homeDirectory, "results.json") + err = os.WriteFile(resultFile, apiResponseBytes, 0644) + if err != nil { + log.Error().Err(err).Msg("failed to write results file " + resultFile) + } + fmt.Println("Results written to " + resultFile) + } + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/content/get_export_status/get_export_status.go b/pkg/cmd/content/get_export_status/get_export_status.go new file mode 100644 index 00000000..befa94a4 --- /dev/null +++ b/pkg/cmd/content/get_export_status/get_export_status.go @@ -0,0 +1,45 @@ +package get_export_status + +import ( + "github.com/antihax/optional" + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdExportStatus(client *cip.APIClient) *cobra.Command { + var ( + contentId string + jobId string + isAdminMode bool + ) + cmd := &cobra.Command{ + Use: "get-export-status", + Short: "Get the status of an asynchronous content export request for the given job identifier", + Run: func(cmd *cobra.Command, args []string) { + exportStatus(contentId, jobId, isAdminMode, client) + }, + } + cmd.Flags().StringVar(&contentId, "contentId", "", "Specify the id of the content item to export") + cmd.Flags().StringVar(&jobId, "jobId", "", "Specify the job id for the export (returned from running sumocli content start-export)") + cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "Set to true if you want to perform the request as a content administrator") + cmd.MarkFlagRequired("contentId") + cmd.MarkFlagRequired("jobId") + return cmd +} + +func exportStatus(contentId string, jobId string, isAdminMode bool, client *cip.APIClient) { + var options types.ContentOpts + if isAdminMode == true { + options.IsAdminMode = optional.NewString("true") + } else { + options.IsAdminMode = optional.NewString("false") + } + apiResponse, httpResponse, errorResponse := client.GetAsyncExportStatus(contentId, jobId, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/content/get_import_status/get_import_status.go b/pkg/cmd/content/get_import_status/get_import_status.go new file mode 100644 index 00000000..5e92f9d4 --- /dev/null +++ b/pkg/cmd/content/get_import_status/get_import_status.go @@ -0,0 +1,45 @@ +package get_import_status + +import ( + "github.com/antihax/optional" + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdGetImportStatus(client *cip.APIClient) *cobra.Command { + var ( + folderId string + jobId string + isAdminMode bool + ) + cmd := &cobra.Command{ + Use: "import-status", + Short: "Get the status of an asynchronous content import request for the given job identifier", + Run: func(cmd *cobra.Command, args []string) { + importStatus(folderId, jobId, isAdminMode, client) + }, + } + cmd.Flags().StringVar(&folderId, "folderId", "", "Specify the id of the folder to import to") + cmd.Flags().StringVar(&jobId, "jobId", "", "Specify the job id for the import (returned from running sumocli content start-import)") + cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "Set to true if you want to perform the request as a content administrator") + cmd.MarkFlagRequired("folderId") + cmd.MarkFlagRequired("jobId") + return cmd +} + +func importStatus(folderId string, jobId string, isAdminMode bool, client *cip.APIClient) { + var options types.ContentOpts + if isAdminMode == true { + options.IsAdminMode = optional.NewString("true") + } else { + options.IsAdminMode = optional.NewString("false") + } + apiResponse, httpResponse, errorResponse := client.GetAsyncImportStatus(folderId, jobId, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/content/import-status/import-status.go b/pkg/cmd/content/import-status/import-status.go deleted file mode 100644 index 155613fe..00000000 --- a/pkg/cmd/content/import-status/import-status.go +++ /dev/null @@ -1,69 +0,0 @@ -package import_status - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdImportStatus() *cobra.Command { - var ( - folderId string - jobId string - isAdminMode bool - ) - - cmd := &cobra.Command{ - Use: "import-status", - Short: "Get the status of an asynchronous content import request for the given job identifier", - Run: func(cmd *cobra.Command, args []string) { - importStatus(folderId, jobId, isAdminMode) - }, - } - cmd.Flags().StringVar(&folderId, "folderId", "", "Specify the id of the folder to import to") - cmd.Flags().StringVar(&jobId, "jobId", "", "Specify the job id for the import (returned from running sumocli content start-import)") - cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "Set to true if you want to perform the request as a content administrator") - cmd.MarkFlagRequired("folderId") - cmd.MarkFlagRequired("jobId") - return cmd -} - -func importStatus(folderId string, jobId string, isAdminMode bool) { - var importStatusResponse api.ExportStatusResponse - log := logging.GetConsoleLogger() - requestUrl := "/v2/content/folders/" + folderId + "/import/" + jobId + "/status" - client, request := factory.NewHttpRequest("GET", requestUrl) - if isAdminMode == true { - request.Header.Add("isAdminMode", "true") - } - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &importStatusResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - importStatusJson, err := json.MarshalIndent(importStatusResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal exportStatusResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(importStatusJson)) - } -} diff --git a/pkg/cmd/content/move/move.go b/pkg/cmd/content/move/move.go index 1dc42b2e..6f52d36e 100644 --- a/pkg/cmd/content/move/move.go +++ b/pkg/cmd/content/move/move.go @@ -1,28 +1,24 @@ package move import ( - "encoding/json" - "fmt" + "github.com/antihax/optional" "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "net/url" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdMove() *cobra.Command { +func NewCmdMove(client *cip.APIClient) *cobra.Command { var ( id string destinationFolderId string isAdminMode bool ) - cmd := &cobra.Command{ Use: "move", Short: "Moves an item from its current location to another folder.", Run: func(cmd *cobra.Command, args []string) { - move(id, destinationFolderId, isAdminMode) + move(id, destinationFolderId, isAdminMode, client) }, } cmd.Flags().StringVar(&id, "id", "", "Specify the id of the content to move") @@ -33,42 +29,17 @@ func NewCmdMove() *cobra.Command { return cmd } -func move(id string, destinationFolderId string, isAdminMode bool) { - var moveResponse api.MoveResponse - log := logging.GetConsoleLogger() - requestUrl := "/v2/content/" + id + "/move" - client, request := factory.NewHttpRequest("POST", requestUrl) +func move(id string, destinationFolderId string, isAdminMode bool, client *cip.APIClient) { + var options types.ContentOpts if isAdminMode == true { - request.Header.Add("isAdminMode", "true") - } - query := url.Values{} - query.Add("destinationFolderId", destinationFolderId) - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to ") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &moveResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - moveJson, err := json.MarshalIndent(moveResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal copyResponse") + options.IsAdminMode = optional.NewString("true") + } else { + options.IsAdminMode = optional.NewString("false") } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - fmt.Println(string(moveJson)) + httpResponse, errorResponse := client.MoveItem(destinationFolderId, id, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) } else { - fmt.Println("Content successfully moved.") + cmdutils.Output(nil, httpResponse, errorResponse, "Content was moved successfully.") } } diff --git a/pkg/cmd/content/start-copy/start-copy.go b/pkg/cmd/content/start-copy/start-copy.go deleted file mode 100644 index de56014e..00000000 --- a/pkg/cmd/content/start-copy/start-copy.go +++ /dev/null @@ -1,73 +0,0 @@ -package start_copy - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "net/url" -) - -func NewCmdStartCopy() *cobra.Command { - var ( - id string - destinationFolder string - isAdminMode bool - ) - - cmd := &cobra.Command{ - Use: "start-copy", - Short: "Start an asynchronous content copy job with the given identifier to the destination folder. If the content item is a folder, everything under the folder is copied recursively.", - Run: func(cmd *cobra.Command, args []string) { - startCopy(id, destinationFolder, isAdminMode) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the content you want to copy") - cmd.Flags().StringVar(&destinationFolder, "destinationFolder", "", "Specify the id of the destination folder") - cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "et to true if you want to perform the request as a content administrator") - cmd.MarkFlagRequired("id") - cmd.MarkFlagRequired("destinationFolder") - return cmd -} - -func startCopy(id string, destinationFolder string, isAdminMode bool) { - var copyResponse api.StartExportResponse - log := logging.GetConsoleLogger() - requestUrl := "/v2/content/" + id + "/copy" - client, request := factory.NewHttpRequest("POST", requestUrl) - if isAdminMode == true { - request.Header.Add("isAdminMode", "true") - } - query := url.Values{} - query.Add("destinationFolder", destinationFolder) - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to ") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, ©Response) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - copyJson, err := json.MarshalIndent(copyResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal copyResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(copyJson)) - } -} diff --git a/pkg/cmd/content/start-deletion/start-deletion.go b/pkg/cmd/content/start-deletion/start-deletion.go deleted file mode 100644 index 4bfdb536..00000000 --- a/pkg/cmd/content/start-deletion/start-deletion.go +++ /dev/null @@ -1,66 +0,0 @@ -package start_deletion - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdStartDeletion() *cobra.Command { - var ( - id string - isAdminMode bool - ) - - cmd := &cobra.Command{ - Use: "start-deletion", - Short: "Start an asynchronous content deletion job with the given identifier.", - Run: func(cmd *cobra.Command, args []string) { - startDeletion(id, isAdminMode) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the content to delete") - cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "Set to true if you want to perform the request as a content administrator") - cmd.MarkFlagRequired("id") - return cmd -} - -func startDeletion(id string, isAdminMode bool) { - var deletionResponse api.StartExportResponse - log := logging.GetConsoleLogger() - requestUrl := "/v2/content/" + id + "/delete" - client, request := factory.NewHttpRequest("DELETE", requestUrl) - if isAdminMode == true { - request.Header.Add("isAdminMode", "true") - } - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &deletionResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - exportJson, err := json.MarshalIndent(deletionResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal exportResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(exportJson)) - } -} diff --git a/pkg/cmd/content/start-export/start-export.go b/pkg/cmd/content/start-export/start-export.go deleted file mode 100644 index 7f9f6a58..00000000 --- a/pkg/cmd/content/start-export/start-export.go +++ /dev/null @@ -1,68 +0,0 @@ -package start_export - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdStartExport() *cobra.Command { - var ( - id string - isAdminMode bool - ) - - cmd := &cobra.Command{ - Use: "start-export", - Short: "Starts an asynchronous export of content with the given identifier. You will be given a job identifier" + - "which can be used with the sumocli content export-status command." + - "If the content is a folder everything under that folder is exported recursively.", - Run: func(cmd *cobra.Command, args []string) { - startExport(id, isAdminMode) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the content item to export") - cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "Set to true if you want to perform the request as a content administrator") - cmd.MarkFlagRequired("id") - return cmd -} - -func startExport(id string, isAdminMode bool) { - var exportResponse api.StartExportResponse - log := logging.GetConsoleLogger() - requestUrl := "/v2/content/" + id + "/export" - client, request := factory.NewHttpRequest("POST", requestUrl) - if isAdminMode == true { - request.Header.Add("isAdminMode", "true") - } - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &exportResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - exportJson, err := json.MarshalIndent(exportResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal exportResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(exportJson)) - } -} diff --git a/pkg/cmd/content/start-import/start-import.go b/pkg/cmd/content/start-import/start-import.go deleted file mode 100644 index beefe90d..00000000 --- a/pkg/cmd/content/start-import/start-import.go +++ /dev/null @@ -1,316 +0,0 @@ -package start_import - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "net/url" - "os" -) - -func NewCmdStartImport() *cobra.Command { - var ( - file string - folderId string - isAdminMode bool - overwrite bool - ) - - cmd := &cobra.Command{ - Use: "start-import", - Short: "Schedule an asynchronous import of content inside an existing folder with the given identifier. The start-import command can be used to create or update content within a folder.", - Run: func(cmd *cobra.Command, args []string) { - startImport(file, folderId, isAdminMode, overwrite) - }, - } - cmd.Flags().StringVar(&file, "file", "", "File path that contains Sumo Logic content in JSON format") - cmd.Flags().StringVar(&folderId, "folderId", "", "Specify the folder ID to import into must be in hexadecimal format. Use sumocli content get-path to get the ID of a folder") - cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "Set to true if you want to perform the request as a content administrator") - cmd.Flags().BoolVar(&overwrite, "overwrite", false, "Set to true if you want to overwrite existing content with the same name") - cmd.MarkFlagRequired("folderId") - return cmd -} - -func startImport(file string, folderId string, isAdminMode bool, overwrite bool) { - var responseType api.ResponseType - var responseId api.StartExportResponse - var responseStatusCode int - var responseBodyData []byte - log := logging.GetConsoleLogger() - requestUrl := "/v2/content/folders/" + folderId + "/import" - fileData, err := os.ReadFile(file) - if err != nil { - log.Fatal().Err(err).Msg("failed to read file") - } - err = json.Unmarshal(fileData, &responseType) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal file data") - } - if responseType.Type == "FolderSyncDefinition" { - var folderSyncDefinition api.FolderSyncDefinition - err = json.Unmarshal(fileData, &folderSyncDefinition) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal file data") - } - requestBody, err := json.Marshal(folderSyncDefinition) - if err != nil { - log.Error().Err(err).Msg("failed to marshal request body") - } - client, request := factory.NewHttpRequestWithBody("POST", requestUrl, requestBody) - if isAdminMode == true { - request.Header.Add("isAdminMode", "true") - } - query := url.Values{} - if overwrite == true { - query.Add("overwrite", "true") - } else { - query.Add("overwrite", "false") - } - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to ") - } - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - responseBodyData = responseBody - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - err = json.Unmarshal(responseBody, &responseId) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - responseStatusCode = response.StatusCode - } else if responseType.Type == "DashboardSyncDefinition" { - var dashboardSyncDefinition api.DashboardSyncDefinition - err = json.Unmarshal(fileData, &dashboardSyncDefinition) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal file data") - } - requestBody, err := json.Marshal(dashboardSyncDefinition) - if err != nil { - log.Error().Err(err).Msg("failed to marshal request body") - } - client, request := factory.NewHttpRequestWithBody("POST", requestUrl, requestBody) - if isAdminMode == true { - request.Header.Add("isAdminMode", "true") - } - query := url.Values{} - if overwrite == true { - query.Add("overwrite", "true") - } else { - query.Add("overwrite", "false") - } - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to ") - } - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - responseBodyData = responseBody - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - err = json.Unmarshal(responseBody, &responseId) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - responseStatusCode = response.StatusCode - } else if responseType.Type == "MewboardSyncDefinition" { - var mewboardSyncDefinition api.MewboardSyncDefinition - err = json.Unmarshal(fileData, &mewboardSyncDefinition) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal file data") - } - requestBody, err := json.Marshal(mewboardSyncDefinition) - if err != nil { - log.Error().Err(err).Msg("failed to marshal request body") - } - client, request := factory.NewHttpRequestWithBody("POST", requestUrl, requestBody) - if isAdminMode == true { - request.Header.Add("isAdminMode", "true") - } - query := url.Values{} - if overwrite == true { - query.Add("overwrite", "true") - } else { - query.Add("overwrite", "false") - } - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to ") - } - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - responseBodyData = responseBody - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - err = json.Unmarshal(responseBody, &responseId) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - responseStatusCode = response.StatusCode - } else if responseType.Type == "SavedSearchWithScheduleSyncDefinition" { - var savedSearchWithScheduleSyncDefinition api.SavedSearchWithScheduleSyncDefinition - err = json.Unmarshal(fileData, &savedSearchWithScheduleSyncDefinition) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal file data") - } - requestBody, err := json.Marshal(savedSearchWithScheduleSyncDefinition) - if err != nil { - log.Error().Err(err).Msg("failed to marshal request body") - } - client, request := factory.NewHttpRequestWithBody("POST", requestUrl, requestBody) - if isAdminMode == true { - request.Header.Add("isAdminMode", "true") - } - query := url.Values{} - if overwrite == true { - query.Add("overwrite", "true") - } else { - query.Add("overwrite", "false") - } - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to ") - } - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - responseBodyData = responseBody - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - err = json.Unmarshal(responseBody, &responseId) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - responseStatusCode = response.StatusCode - } else if responseType.Type == "MetricsSavedSearchSyncDefinition" { - var metricsSavedSearchSyncDefinition api.MetricsSavedSearchSyncDefinition - err = json.Unmarshal(fileData, &metricsSavedSearchSyncDefinition) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal file data") - } - requestBody, err := json.Marshal(metricsSavedSearchSyncDefinition) - if err != nil { - log.Error().Err(err).Msg("failed to marshal request body") - } - client, request := factory.NewHttpRequestWithBody("POST", requestUrl, requestBody) - if isAdminMode == true { - request.Header.Add("isAdminMode", "true") - } - query := url.Values{} - if overwrite == true { - query.Add("overwrite", "true") - } else { - query.Add("overwrite", "false") - } - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to ") - } - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - responseBodyData = responseBody - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - err = json.Unmarshal(responseBody, &responseId) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - responseStatusCode = response.StatusCode - } else if responseType.Type == "MetricsSearchSyncDefinition" { - var metricsSearchSyncDefinition api.MetricsSearchSyncDefinition - err = json.Unmarshal(fileData, &metricsSearchSyncDefinition) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal file data") - } - requestBody, err := json.Marshal(metricsSearchSyncDefinition) - if err != nil { - log.Error().Err(err).Msg("failed to marshal request body") - } - client, request := factory.NewHttpRequestWithBody("POST", requestUrl, requestBody) - if isAdminMode == true { - request.Header.Add("isAdminMode", "true") - } - query := url.Values{} - if overwrite == true { - query.Add("overwrite", "true") - } else { - query.Add("overwrite", "false") - } - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to ") - } - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - responseBodyData = responseBody - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - err = json.Unmarshal(responseBody, &responseId) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - responseStatusCode = response.StatusCode - } else if responseType.Type == "LookupTableSyncDefinition" { - var lookupTableSyncDefinition api.LookupTableSyncDefinition - err = json.Unmarshal(fileData, &lookupTableSyncDefinition) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal file data") - } - requestBody, err := json.Marshal(lookupTableSyncDefinition) - if err != nil { - log.Error().Err(err).Msg("failed to marshal request body") - } - client, request := factory.NewHttpRequestWithBody("POST", requestUrl, requestBody) - if isAdminMode == true { - request.Header.Add("isAdminMode", "true") - } - query := url.Values{} - if overwrite == true { - query.Add("overwrite", "true") - } else { - query.Add("overwrite", "false") - } - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to ") - } - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - responseBodyData = responseBody - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - err = json.Unmarshal(responseBody, &responseId) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - responseStatusCode = response.StatusCode - } - - responseIdJson, err := json.MarshalIndent(responseId, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal responseId") - } - if responseStatusCode != 200 { - factory.HttpError(responseStatusCode, responseBodyData, log) - } else { - fmt.Println(string(responseIdJson)) - } -} diff --git a/pkg/cmd/content/start_copy/start_copy.go b/pkg/cmd/content/start_copy/start_copy.go new file mode 100644 index 00000000..5ba25d45 --- /dev/null +++ b/pkg/cmd/content/start_copy/start_copy.go @@ -0,0 +1,45 @@ +package start_copy + +import ( + "github.com/antihax/optional" + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdStartCopy(client *cip.APIClient) *cobra.Command { + var ( + id string + destinationFolder string + isAdminMode bool + ) + cmd := &cobra.Command{ + Use: "start-copy", + Short: "Start an asynchronous content copy job with the given identifier to the destination folder. If the content item is a folder, everything under the folder is copied recursively.", + Run: func(cmd *cobra.Command, args []string) { + startCopy(id, destinationFolder, isAdminMode, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the content you want to copy") + cmd.Flags().StringVar(&destinationFolder, "destinationFolder", "", "Specify the id of the destination folder") + cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "et to true if you want to perform the request as a content administrator") + cmd.MarkFlagRequired("id") + cmd.MarkFlagRequired("destinationFolder") + return cmd +} + +func startCopy(id string, destinationFolder string, isAdminMode bool, client *cip.APIClient) { + var options types.ContentOpts + if isAdminMode == true { + options.IsAdminMode = optional.NewString("true") + } else { + options.IsAdminMode = optional.NewString("false") + } + apiResponse, httpResponse, errorResponse := client.BeginAsyncCopy(id, destinationFolder, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/content/start_deletion/start_deletion.go b/pkg/cmd/content/start_deletion/start_deletion.go new file mode 100644 index 00000000..1eb1f91a --- /dev/null +++ b/pkg/cmd/content/start_deletion/start_deletion.go @@ -0,0 +1,42 @@ +package start_deletion + +import ( + "github.com/antihax/optional" + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdStartDeletion(client *cip.APIClient) *cobra.Command { + var ( + id string + isAdminMode bool + ) + cmd := &cobra.Command{ + Use: "start-deletion", + Short: "Start an asynchronous content deletion job with the given identifier.", + Run: func(cmd *cobra.Command, args []string) { + startDeletion(id, isAdminMode, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the content to delete") + cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "Set to true if you want to perform the request as a content administrator") + cmd.MarkFlagRequired("id") + return cmd +} + +func startDeletion(id string, isAdminMode bool, client *cip.APIClient) { + var options types.ContentOpts + if isAdminMode == true { + options.IsAdminMode = optional.NewString("true") + } else { + options.IsAdminMode = optional.NewString("false") + } + apiResponse, httpResponse, errorResponse := client.BeginAsyncDelete(id, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/content/start_export/start_export.go b/pkg/cmd/content/start_export/start_export.go new file mode 100644 index 00000000..59a0cfeb --- /dev/null +++ b/pkg/cmd/content/start_export/start_export.go @@ -0,0 +1,44 @@ +package start_export + +import ( + "github.com/antihax/optional" + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdStartExport(client *cip.APIClient) *cobra.Command { + var ( + id string + isAdminMode bool + ) + cmd := &cobra.Command{ + Use: "start-export", + Short: "Starts an asynchronous export of content with the given identifier. You will be given a job identifier" + + "which can be used with the sumocli content export-status command." + + "If the content is a folder everything under that folder is exported recursively.", + Run: func(cmd *cobra.Command, args []string) { + startExport(id, isAdminMode, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the content item to export") + cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "Set to true if you want to perform the request as a content administrator") + cmd.MarkFlagRequired("id") + return cmd +} + +func startExport(id string, isAdminMode bool, client *cip.APIClient) { + var options types.ContentOpts + if isAdminMode == true { + options.IsAdminMode = optional.NewString("true") + } else { + options.IsAdminMode = optional.NewString("false") + } + apiResponse, httpResponse, errorResponse := client.BeginAsyncExport(id, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/content/start_import/start_import.go b/pkg/cmd/content/start_import/start_import.go new file mode 100644 index 00000000..b7661fea --- /dev/null +++ b/pkg/cmd/content/start_import/start_import.go @@ -0,0 +1,140 @@ +package start_import + +import ( + "encoding/json" + "github.com/antihax/optional" + "github.com/rs/zerolog/log" + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" + "os" +) + +func NewCmdStartImport(client *cip.APIClient) *cobra.Command { + var ( + file string + folderId string + isAdminMode bool + overwrite bool + ) + cmd := &cobra.Command{ + Use: "start-import", + Short: "Schedule an asynchronous import of content inside an existing folder with the given identifier. The start-import command can be used to create or update content within a folder.", + Run: func(cmd *cobra.Command, args []string) { + startImport(file, folderId, isAdminMode, overwrite, client) + }, + } + cmd.Flags().StringVar(&file, "file", "", "File path that contains Sumo Logic content in JSON format") + cmd.Flags().StringVar(&folderId, "folderId", "", "Specify the folder ID to import into must be in hexadecimal format. Use sumocli content get-path to get the ID of a folder") + cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "Set to true if you want to perform the request as a content administrator") + cmd.Flags().BoolVar(&overwrite, "overwrite", false, "Set to true if you want to overwrite existing content with the same name") + cmd.MarkFlagRequired("folderId") + return cmd +} + +func startImport(file string, folderId string, isAdminMode bool, overwrite bool, client *cip.APIClient) { + var ( + contentType types.ContentSyncDefinition + options types.ContentImportOpts + ) + if isAdminMode == true { + options.IsAdminMode = optional.NewString("true") + } else { + options.IsAdminMode = optional.NewString("false") + } + options.Overwrite = optional.NewBool(overwrite) + fileData, err := os.ReadFile(file) + if err != nil { + log.Fatal().Err(err).Msg("failed to read file") + } + err = json.Unmarshal(fileData, &contentType) + if err != nil { + log.Fatal().Err(err).Msg("failed to unmarshal file data") + } + if contentType.Type_ == "FolderSyncDefinition" { + var folderContent types.FolderSyncDefinition + err = json.Unmarshal(fileData, &folderContent) + if err != nil { + log.Fatal().Err(err).Msg("failed to unmarshal file data") + } + apiResponse, httpResponse, errorResponse := client.BeginFolderAsyncImport(folderContent, folderId, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + } else if contentType.Type_ == "DashboardSyncDefinition" { + var dashboardContent types.DashboardSyncDefinition + err = json.Unmarshal(fileData, &dashboardContent) + if err != nil { + log.Fatal().Err(err).Msg("failed to unmarshal file data") + } + apiResponse, httpResponse, errorResponse := client.BeginDashboardAsyncImport(dashboardContent, folderId, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + } else if contentType.Type_ == "MewboardSyncDefinition" { + var mewboardContent types.MewboardSyncDefinition + err = json.Unmarshal(fileData, &mewboardContent) + if err != nil { + log.Fatal().Err(err).Msg("failed to unmarshal file data") + } + apiResponse, httpResponse, errorResponse := client.BeginMewboardAsyncImport(mewboardContent, folderId, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + } else if contentType.Type_ == "SavedSearchWithScheduleSyncDefinition" { + var savedSearchContent types.SavedSearchWithScheduleSyncDefinition + err = json.Unmarshal(fileData, &savedSearchContent) + if err != nil { + log.Fatal().Err(err).Msg("failed to unmarshal file data") + } + apiResponse, httpResponse, errorResponse := client.BeginSavedSearchAsyncImport(savedSearchContent, folderId, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + } else if contentType.Type_ == "MetricsSavedSearchSyncDefinition" { + var metricsSavedSearchContent types.MetricsSavedSearchSyncDefinition + err = json.Unmarshal(fileData, &metricsSavedSearchContent) + if err != nil { + log.Fatal().Err(err).Msg("failed to unmarshal file data") + } + apiResponse, httpResponse, errorResponse := client.BeginMetricsSavedSearchAsyncImport(metricsSavedSearchContent, folderId, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + } else if contentType.Type_ == "MetricsSearchSyncDefinition" { + var metricsSearchContent types.MetricsSearchSyncDefinition + err = json.Unmarshal(fileData, &metricsSearchContent) + if err != nil { + log.Fatal().Err(err).Msg("failed to unmarshal file data") + } + apiResponse, httpResponse, errorResponse := client.BeginMetricsSearchAsyncImport(metricsSearchContent, folderId, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + } else if contentType.Type_ == "LookupTableSyncDefinition" { + var lookupTableContent types.LookupTableSyncDefinition + err = json.Unmarshal(fileData, &lookupTableContent) + if err != nil { + log.Fatal().Err(err).Msg("failed to unmarshal file data") + } + apiResponse, httpResponse, errorResponse := client.BeginLookupTableAsyncImport(lookupTableContent, folderId, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + } +} diff --git a/pkg/cmd/dashboards/create/create.go b/pkg/cmd/dashboards/create/create.go index cfb985d7..360567af 100644 --- a/pkg/cmd/dashboards/create/create.go +++ b/pkg/cmd/dashboards/create/create.go @@ -2,23 +2,24 @@ package create import ( "encoding/json" - "fmt" + "github.com/rs/zerolog/log" "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" "os" ) -func NewCmdDashboardsCreate() *cobra.Command { +func NewCmdDashboardsCreate(client *cip.APIClient) *cobra.Command { var file string cmd := &cobra.Command{ Use: "create", Short: "Creates a new dashboard.", + Long: "Note: When exporting a dashboard spec from the Sumo Logic portal ensure that you have the timeRange.to object set as well as the " + + "timeRange.from set otherwise you will get errors when trying to create.", Run: func(cmd *cobra.Command, args []string) { - createDashboard(file) + createDashboard(file, client) }, } cmd.Flags().StringVar(&file, "file", "", "Specify the full file path to a json file containing a dashboard definition."+ @@ -27,48 +28,20 @@ func NewCmdDashboardsCreate() *cobra.Command { return cmd } -func createDashboard(file string) { - var dashboardResponse api.GetDashboard - var dashboardRequest api.CreateDashboard - log := logging.GetConsoleLogger() +func createDashboard(file string, client *cip.APIClient) { + var dashboardDefinition types.DashboardRequest fileData, err := os.ReadFile(file) if err != nil { log.Error().Err(err).Msg("failed to read file " + file) } - err = json.Unmarshal(fileData, &dashboardRequest) + err = json.Unmarshal(fileData, &dashboardDefinition) if err != nil { log.Error().Err(err).Msg("failed to unmarshal file") } - requestBody, err := json.Marshal(dashboardRequest) - if err != nil { - log.Error().Err(err).Msg("error marshalling request body") - } - requestUrl := "/v2/dashboards" - client, request := factory.NewHttpRequestWithBody("POST", requestUrl, requestBody) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &dashboardResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - dashboardResponseJson, err := json.MarshalIndent(dashboardResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal foldersResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) + apiResponse, httpResponse, errorResponse := client.CreateDashboard(dashboardDefinition) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) } else { - fmt.Println(string(dashboardResponseJson)) + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } } diff --git a/pkg/cmd/dashboards/dashboards.go b/pkg/cmd/dashboards/dashboards.go index 92238959..fa727df3 100644 --- a/pkg/cmd/dashboards/dashboards.go +++ b/pkg/cmd/dashboards/dashboards.go @@ -6,17 +6,18 @@ import ( NewCmdDashboardDelete "github.com/wizedkyle/sumocli/pkg/cmd/dashboards/delete" NewCmdDashboardsGet "github.com/wizedkyle/sumocli/pkg/cmd/dashboards/get" NewCmdDashboardsUpdate "github.com/wizedkyle/sumocli/pkg/cmd/dashboards/update" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdDashboards() *cobra.Command { +func NewCmdDashboards(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "dashboards", Short: "Manage dashboards (New)", Long: "Commands that allow you to create, modify or delete new dashboards.", } - cmd.AddCommand(NewCmdDashboardCreate.NewCmdDashboardsCreate()) - cmd.AddCommand(NewCmdDashboardDelete.NewCmdDashboardsDelete()) - cmd.AddCommand(NewCmdDashboardsGet.NewCmdDashboardsGet()) - cmd.AddCommand(NewCmdDashboardsUpdate.NewCmdDashboardsUpdate()) + cmd.AddCommand(NewCmdDashboardCreate.NewCmdDashboardsCreate(client)) + cmd.AddCommand(NewCmdDashboardDelete.NewCmdDashboardsDelete(client)) + cmd.AddCommand(NewCmdDashboardsGet.NewCmdDashboardsGet(client)) + cmd.AddCommand(NewCmdDashboardsUpdate.NewCmdDashboardsUpdate(client)) return cmd } diff --git a/pkg/cmd/dashboards/delete/delete.go b/pkg/cmd/dashboards/delete/delete.go index ede43b8b..9cf094c9 100644 --- a/pkg/cmd/dashboards/delete/delete.go +++ b/pkg/cmd/dashboards/delete/delete.go @@ -1,23 +1,18 @@ package delete import ( - "encoding/json" - "fmt" "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdDashboardsDelete() *cobra.Command { +func NewCmdDashboardsDelete(client *cip.APIClient) *cobra.Command { var id string - cmd := &cobra.Command{ Use: "delete", Short: "Delete a dashboard by the given identifier.", Run: func(cmd *cobra.Command, args []string) { - deleteDashboards(id) + deleteDashboards(id, client) }, } cmd.Flags().StringVar(&id, "id", "", "Specify the id of the dashboard") @@ -25,28 +20,11 @@ func NewCmdDashboardsDelete() *cobra.Command { return cmd } -func deleteDashboards(id string) { - log := logging.GetConsoleLogger() - requestUrl := "/v2/dashboards/" + id - client, request := factory.NewHttpRequest("DELETE", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - if response.StatusCode != 204 { - var responseError api.ResponseError - err := json.Unmarshal(responseBody, &responseError) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } +func deleteDashboards(id string, client *cip.APIClient) { + httpResponse, errorResponse := client.DeleteDashboard(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) } else { - fmt.Println("Dashboard was deleted.") + cmdutils.Output(nil, httpResponse, errorResponse, "Dashboard was deleted successfully.") } } diff --git a/pkg/cmd/dashboards/get/get.go b/pkg/cmd/dashboards/get/get.go index 45141f2d..1891b7ec 100644 --- a/pkg/cmd/dashboards/get/get.go +++ b/pkg/cmd/dashboards/get/get.go @@ -1,23 +1,18 @@ package get import ( - "encoding/json" - "fmt" "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdDashboardsGet() *cobra.Command { +func NewCmdDashboardsGet(client *cip.APIClient) *cobra.Command { var id string - cmd := &cobra.Command{ Use: "get", Short: "Get a dashboard by the given identifier.", Run: func(cmd *cobra.Command, args []string) { - getDashboards(id) + getDashboards(id, client) }, } cmd.Flags().StringVar(&id, "id", "", "Specify the id of the dashboard") @@ -25,35 +20,11 @@ func NewCmdDashboardsGet() *cobra.Command { return cmd } -func getDashboards(id string) { - var dashboardResponse api.GetDashboard - log := logging.GetConsoleLogger() - requestUrl := "/v2/dashboards/" + id - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &dashboardResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - dashboardResponseJson, err := json.MarshalIndent(dashboardResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal foldersResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) +func getDashboards(id string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.GetDashboard(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) } else { - fmt.Println(string(dashboardResponseJson)) + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } } diff --git a/pkg/cmd/dashboards/update/update.go b/pkg/cmd/dashboards/update/update.go index dd2aad54..2b321a78 100644 --- a/pkg/cmd/dashboards/update/update.go +++ b/pkg/cmd/dashboards/update/update.go @@ -2,16 +2,15 @@ package update import ( "encoding/json" - "fmt" + "github.com/rs/zerolog/log" "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" "os" ) -func NewCmdDashboardsUpdate() *cobra.Command { +func NewCmdDashboardsUpdate(client *cip.APIClient) *cobra.Command { var ( id string file string @@ -21,7 +20,7 @@ func NewCmdDashboardsUpdate() *cobra.Command { Use: "update", Short: "Update a dashboard by the given identifier.", Run: func(cmd *cobra.Command, args []string) { - updateDashboard(file, id) + updateDashboard(file, id, client) }, } cmd.Flags().StringVar(&file, "file", "", "Specify the full file path to a json file containing a dashboard definition."+ @@ -33,48 +32,20 @@ func NewCmdDashboardsUpdate() *cobra.Command { return cmd } -func updateDashboard(file string, id string) { - var dashboardResponse api.GetDashboard - var dashboardRequest api.CreateDashboard - log := logging.GetConsoleLogger() +func updateDashboard(file string, id string, client *cip.APIClient) { + var dashboardDefinition types.DashboardRequest fileData, err := os.ReadFile(file) if err != nil { log.Error().Err(err).Msg("failed to read file " + file) } - err = json.Unmarshal(fileData, &dashboardRequest) + err = json.Unmarshal(fileData, &dashboardDefinition) if err != nil { log.Error().Err(err).Msg("failed to unmarshal file") } - requestBody, err := json.Marshal(dashboardRequest) - if err != nil { - log.Error().Err(err).Msg("error marshalling request body") - } - requestUrl := "/v2/dashboards/" + id - client, request := factory.NewHttpRequestWithBody("PUT", requestUrl, requestBody) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &dashboardResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - dashboardResponseJson, err := json.MarshalIndent(dashboardResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal foldersResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) + apiResponse, httpResponse, errorResponse := client.UpdateDashboard(dashboardDefinition, id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) } else { - fmt.Println(string(dashboardResponseJson)) + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } } diff --git a/pkg/cmd/dynamic-parsing/create/create.go b/pkg/cmd/dynamic-parsing/create/create.go deleted file mode 100644 index c509f064..00000000 --- a/pkg/cmd/dynamic-parsing/create/create.go +++ /dev/null @@ -1,76 +0,0 @@ -package create - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdDynamicParsingCreate() *cobra.Command { - var ( - name string - scope string - enabled bool - ) - - cmd := &cobra.Command{ - Use: "create", - Short: "Create a new dynamic parsing rule.", - Run: func(cmd *cobra.Command, args []string) { - createDynamicParsingRule(name, scope, enabled) - }, - } - cmd.Flags().StringVar(&name, "name", "", "Specify the name of the dynamic parsing rule") - cmd.Flags().StringVar(&scope, "scope", "", "Scope of the dynamic parsing rule. "+ - "This could be a sourceCategory, sourceHost, or any other metadata that describes the data you want to extract from.") - cmd.Flags().BoolVar(&enabled, "enabled", true, "Set to false if you don't want to enable the rule") - cmd.MarkFlagRequired("name") - cmd.MarkFlagRequired("scope") - return cmd -} - -func createDynamicParsingRule(name string, scope string, enabled bool) { - var dynamicParsingRuleResponse api.DynamicParsingRules - log := logging.GetConsoleLogger() - requestBodySchema := &api.CreateDynamicParsingRule{ - Name: name, - Scope: scope, - Enabled: enabled, - } - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("error marshalling request body") - } - requestUrl := "/v1/dynamicParsingRules" - client, request := factory.NewHttpRequestWithBody("POST", requestUrl, requestBody) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &dynamicParsingRuleResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - dynamicParsingRuleResponseJson, err := json.MarshalIndent(dynamicParsingRuleResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal lookupTableResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(dynamicParsingRuleResponseJson)) - } -} diff --git a/pkg/cmd/dynamic-parsing/delete/delete.go b/pkg/cmd/dynamic-parsing/delete/delete.go deleted file mode 100644 index 8cb0d463..00000000 --- a/pkg/cmd/dynamic-parsing/delete/delete.go +++ /dev/null @@ -1,52 +0,0 @@ -package delete - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdDynamicParsingDelete() *cobra.Command { - var id string - - cmd := &cobra.Command{ - Use: "delete", - Short: "Delete a dynamic parsing rule with the given identifier.", - Run: func(cmd *cobra.Command, args []string) { - deleteDynamicParsingRules(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the dynamic parsing rule") - cmd.MarkFlagRequired("id") - return cmd -} - -func deleteDynamicParsingRules(id string) { - log := logging.GetConsoleLogger() - requestUrl := "/v1/dynamicParsingRules/" + id - client, request := factory.NewHttpRequest("DELETE", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - if response.StatusCode != 204 { - var responseError api.ResponseError - err := json.Unmarshal(responseBody, &responseError) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - } else { - fmt.Println("Dynamic Parsing rule was deleted successfully.") - } -} diff --git a/pkg/cmd/dynamic-parsing/get/get.go b/pkg/cmd/dynamic-parsing/get/get.go deleted file mode 100644 index 90dc9b3f..00000000 --- a/pkg/cmd/dynamic-parsing/get/get.go +++ /dev/null @@ -1,59 +0,0 @@ -package get - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdDynamicParsingGet() *cobra.Command { - var id string - - cmd := &cobra.Command{ - Use: "get", - Short: "Get a dynamic parsing rule with the given identifier.", - Run: func(cmd *cobra.Command, args []string) { - getDynamicParsingRules(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the dynamic parsing rule") - cmd.MarkFlagRequired("id") - return cmd -} - -func getDynamicParsingRules(id string) { - var dynamicParsingRulesResponse api.DynamicParsingRules - log := logging.GetConsoleLogger() - requestUrl := "/v1/dynamicParsingRules/" + id - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &dynamicParsingRulesResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - dynamicParsingRulesResponseJson, err := json.MarshalIndent(dynamicParsingRulesResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(dynamicParsingRulesResponseJson)) - } -} diff --git a/pkg/cmd/dynamic-parsing/list/list.go b/pkg/cmd/dynamic-parsing/list/list.go deleted file mode 100644 index 3f0c5b99..00000000 --- a/pkg/cmd/dynamic-parsing/list/list.go +++ /dev/null @@ -1,65 +0,0 @@ -package list - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "net/url" - "strconv" -) - -func NewCmdDynamicParsingList() *cobra.Command { - var ( - limit int - ) - - cmd := &cobra.Command{ - Use: "list", - Short: "Get a list of all dynamic parsing rules.", - Run: func(cmd *cobra.Command, args []string) { - listDynamicParsingRules(limit) - }, - } - cmd.Flags().IntVar(&limit, "limit", 100, "Specify the number of results to return maximum is 1000") - return cmd -} - -func listDynamicParsingRules(limit int) { - var dynamicParsingRulesResponse api.ListDynamicParsingRules - log := logging.GetConsoleLogger() - requestUrl := "/v1/dynamicParsingRules" - client, request := factory.NewHttpRequest("GET", requestUrl) - query := url.Values{} - query.Add("limit", strconv.Itoa(limit)) - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &dynamicParsingRulesResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - dynamicParsingRulesResponseJson, err := json.MarshalIndent(dynamicParsingRulesResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(dynamicParsingRulesResponseJson)) - } -} diff --git a/pkg/cmd/dynamic-parsing/update/update.go b/pkg/cmd/dynamic-parsing/update/update.go deleted file mode 100644 index 9dde55e1..00000000 --- a/pkg/cmd/dynamic-parsing/update/update.go +++ /dev/null @@ -1,150 +0,0 @@ -package update - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "strconv" - "strings" -) - -func NewCmdDynamicParsingUpdate() *cobra.Command { - var ( - id string - name string - scope string - enabled bool - merge bool - ) - - cmd := &cobra.Command{ - Use: "update", - Short: "Update an existing dynamic parsing rule", - Run: func(cmd *cobra.Command, args []string) { - updateDynamicParsingRule(id, name, scope, enabled, merge) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the dynamic parsing rule") - cmd.Flags().BoolVar(&merge, "merge", true, "If set to false it will overwrite the dynamic parsing rule configuration") - cmd.Flags().StringVar(&name, "name", "", "Specify the name of the dynamic parsing rule") - cmd.Flags().StringVar(&scope, "scope", "", "Scope of the dynamic parsing rule. "+ - "This could be a sourceCategory, sourceHost, or any other metadata that describes the data you want to extract from.") - cmd.Flags().BoolVar(&enabled, "enabled", true, "Set to false if you don't want to enable the rule") - cmd.MarkFlagRequired("id") - cmd.MarkFlagRequired("name") - cmd.MarkFlagRequired("scope") - return cmd -} - -func updateDynamicParsingRule(id string, name string, scope string, enabled bool, merge bool) { - var dynamicParsingRuleResponse api.DynamicParsingRules - log := logging.GetConsoleLogger() - if merge == true { - requestUrl := "/v1/dynamicParsingRules/" + id - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request " + requestUrl) - } - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("error reading response body from request") - } - err = json.Unmarshal(responseBody, &dynamicParsingRuleResponse) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - if response.StatusCode != 200 { - log.Fatal().Msg("Error code = " + strconv.Itoa(response.StatusCode) + string(responseBody)) - } - - // Building body payload to update the ingest budget based on the differences - // between the current ingest budget and the desired settings - requestBodySchema := &api.CreateDynamicParsingRule{} - if strings.EqualFold(dynamicParsingRuleResponse.Name, name) { - requestBodySchema.Name = dynamicParsingRuleResponse.Name - } else { - requestBodySchema.Name = name - } - - if strings.EqualFold(dynamicParsingRuleResponse.Scope, scope) { - requestBodySchema.Scope = dynamicParsingRuleResponse.Scope - } else { - requestBodySchema.Scope = scope - } - - if dynamicParsingRuleResponse.Enabled == enabled { - requestBodySchema.Enabled = dynamicParsingRuleResponse.Enabled - } else { - requestBodySchema.Enabled = enabled - } - - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("failed to marshal request body") - } - client, request = factory.NewHttpRequestWithBody("PUT", requestUrl, requestBody) - response, err = client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request " + requestUrl) - } - defer response.Body.Close() - responseBody, err = io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("error reading response body from request") - } - err = json.Unmarshal(responseBody, &dynamicParsingRuleResponse) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - dynamicParsingRuleResponseJson, err := json.MarshalIndent(dynamicParsingRuleResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("error marshalling response body") - } - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(dynamicParsingRuleResponseJson)) - } - } else { - requestBodySchema := &api.CreateDynamicParsingRule{ - Name: name, - Scope: scope, - Enabled: enabled, - } - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("failed to marshal request body") - } - requestUrl := "/v1/dynamicParsingRules/" + id - client, request := factory.NewHttpRequestWithBody("PUT", requestUrl, requestBody) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("error reading response body from request") - } - err = json.Unmarshal(responseBody, &dynamicParsingRuleResponse) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - dynamicParsingRuleResponseJson, err := json.MarshalIndent(dynamicParsingRuleResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("error marshalling response body") - } - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(dynamicParsingRuleResponseJson)) - } - } -} diff --git a/pkg/cmd/dynamic_parsing/create/create.go b/pkg/cmd/dynamic_parsing/create/create.go new file mode 100644 index 00000000..cf7532e6 --- /dev/null +++ b/pkg/cmd/dynamic_parsing/create/create.go @@ -0,0 +1,43 @@ +package create + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdDynamicParsingCreate(client *cip.APIClient) *cobra.Command { + var ( + name string + scope string + enabled bool + ) + cmd := &cobra.Command{ + Use: "create", + Short: "Create a new dynamic parsing rule.", + Run: func(cmd *cobra.Command, args []string) { + createDynamicParsingRule(name, scope, enabled, client) + }, + } + cmd.Flags().StringVar(&name, "name", "", "Specify the name of the dynamic parsing rule") + cmd.Flags().StringVar(&scope, "scope", "", "Scope of the dynamic parsing rule. "+ + "This could be a sourceCategory, sourceHost, or any other metadata that describes the data you want to extract from.") + cmd.Flags().BoolVar(&enabled, "enabled", true, "Set to false if you don't want to enable the rule") + cmd.MarkFlagRequired("name") + cmd.MarkFlagRequired("scope") + return cmd +} + +func createDynamicParsingRule(name string, scope string, enabled bool, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.CreateDynamicParsingRule(types.DynamicRuleDefinition{ + Name: name, + Scope: scope, + Enabled: enabled, + }) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/dynamic_parsing/delete/delete.go b/pkg/cmd/dynamic_parsing/delete/delete.go new file mode 100644 index 00000000..37fddc65 --- /dev/null +++ b/pkg/cmd/dynamic_parsing/delete/delete.go @@ -0,0 +1,30 @@ +package delete + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdDynamicParsingDelete(client *cip.APIClient) *cobra.Command { + var id string + cmd := &cobra.Command{ + Use: "delete", + Short: "Delete a dynamic parsing rule with the given identifier.", + Run: func(cmd *cobra.Command, args []string) { + deleteDynamicParsingRules(id, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the dynamic parsing rule") + cmd.MarkFlagRequired("id") + return cmd +} + +func deleteDynamicParsingRules(id string, client *cip.APIClient) { + httpResponse, errorResponse := client.DeleteDynamicParsingRule(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(nil, httpResponse, errorResponse, "Dynamic Parsing rule was deleted successfully.") + } +} diff --git a/pkg/cmd/dynamic-parsing/dynamic-parsing.go b/pkg/cmd/dynamic_parsing/dynamic-parsing.go similarity index 75% rename from pkg/cmd/dynamic-parsing/dynamic-parsing.go rename to pkg/cmd/dynamic_parsing/dynamic-parsing.go index edcbe800..8cafb1fb 100644 --- a/pkg/cmd/dynamic-parsing/dynamic-parsing.go +++ b/pkg/cmd/dynamic_parsing/dynamic-parsing.go @@ -2,23 +2,24 @@ package dynamic_parsing import ( "github.com/spf13/cobra" - NewCmdDynamicParsingCreate "github.com/wizedkyle/sumocli/pkg/cmd/dynamic-parsing/create" - NewCmdDynamicParsingDelete "github.com/wizedkyle/sumocli/pkg/cmd/dynamic-parsing/delete" - NewCmdDynamicParsingGet "github.com/wizedkyle/sumocli/pkg/cmd/dynamic-parsing/get" - NewCmdDynamicParsingList "github.com/wizedkyle/sumocli/pkg/cmd/dynamic-parsing/list" - NewCmdDynamicParsingUpdate "github.com/wizedkyle/sumocli/pkg/cmd/dynamic-parsing/update" + NewCmdDynamicParsingCreate "github.com/wizedkyle/sumocli/pkg/cmd/dynamic_parsing/create" + NewCmdDynamicParsingDelete "github.com/wizedkyle/sumocli/pkg/cmd/dynamic_parsing/delete" + NewCmdDynamicParsingGet "github.com/wizedkyle/sumocli/pkg/cmd/dynamic_parsing/get" + NewCmdDynamicParsingList "github.com/wizedkyle/sumocli/pkg/cmd/dynamic_parsing/list" + NewCmdDynamicParsingUpdate "github.com/wizedkyle/sumocli/pkg/cmd/dynamic_parsing/update" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdDynamicParsing() *cobra.Command { +func NewCmdDynamicParsing(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "dynamic-parsing", Short: "Manage dynamic parsing rules", Long: "Dynamic Parsing allows automatic field extraction from your log messages when you run a search.", } - cmd.AddCommand(NewCmdDynamicParsingCreate.NewCmdDynamicParsingCreate()) - cmd.AddCommand(NewCmdDynamicParsingDelete.NewCmdDynamicParsingDelete()) - cmd.AddCommand(NewCmdDynamicParsingGet.NewCmdDynamicParsingGet()) - cmd.AddCommand(NewCmdDynamicParsingList.NewCmdDynamicParsingList()) - cmd.AddCommand(NewCmdDynamicParsingUpdate.NewCmdDynamicParsingUpdate()) + cmd.AddCommand(NewCmdDynamicParsingCreate.NewCmdDynamicParsingCreate(client)) + cmd.AddCommand(NewCmdDynamicParsingDelete.NewCmdDynamicParsingDelete(client)) + cmd.AddCommand(NewCmdDynamicParsingGet.NewCmdDynamicParsingGet(client)) + cmd.AddCommand(NewCmdDynamicParsingList.NewCmdDynamicParsingList(client)) + cmd.AddCommand(NewCmdDynamicParsingUpdate.NewCmdDynamicParsingUpdate(client)) return cmd } diff --git a/pkg/cmd/dynamic_parsing/get/get.go b/pkg/cmd/dynamic_parsing/get/get.go new file mode 100644 index 00000000..2cfedbc3 --- /dev/null +++ b/pkg/cmd/dynamic_parsing/get/get.go @@ -0,0 +1,30 @@ +package get + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdDynamicParsingGet(client *cip.APIClient) *cobra.Command { + var id string + cmd := &cobra.Command{ + Use: "get", + Short: "Get a dynamic parsing rule with the given identifier.", + Run: func(cmd *cobra.Command, args []string) { + getDynamicParsingRules(id, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the dynamic parsing rule") + cmd.MarkFlagRequired("id") + return cmd +} + +func getDynamicParsingRules(id string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.GetDynamicParsingRule(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/dynamic_parsing/list/list.go b/pkg/cmd/dynamic_parsing/list/list.go new file mode 100644 index 00000000..4b0d59dd --- /dev/null +++ b/pkg/cmd/dynamic_parsing/list/list.go @@ -0,0 +1,50 @@ +package list + +import ( + "github.com/antihax/optional" + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdDynamicParsingList(client *cip.APIClient) *cobra.Command { + var limit int32 + cmd := &cobra.Command{ + Use: "list", + Short: "Get a list of all dynamic parsing rules.", + Run: func(cmd *cobra.Command, args []string) { + listDynamicParsingRules(limit, client) + }, + } + cmd.Flags().Int32Var(&limit, "limit", 100, "Specify the number of results to return maximum is 1000") + return cmd +} + +func listDynamicParsingRules(limit int32, client *cip.APIClient) { + var options types.DynamicParsingRuleOpts + var paginationToken string + options.Limit = optional.NewInt32(limit) + apiResponse, httpResponse, errorResponse := client.ListDynamicParsingRules(&options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + paginationToken = apiResponse.Next + for paginationToken != "" { + apiResponse = listDynamicRulesPagination(client, options, paginationToken) + paginationToken = apiResponse.Next + } +} + +func listDynamicRulesPagination(client *cip.APIClient, options types.DynamicParsingRuleOpts, token string) types.ListDynamicRulesResponse { + options.Token = optional.NewString(token) + apiResponse, httpResponse, errorResponse := client.ListDynamicParsingRules(&options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + return apiResponse +} diff --git a/pkg/cmd/dynamic_parsing/update/update.go b/pkg/cmd/dynamic_parsing/update/update.go new file mode 100644 index 00000000..1f534eeb --- /dev/null +++ b/pkg/cmd/dynamic_parsing/update/update.go @@ -0,0 +1,47 @@ +package update + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdDynamicParsingUpdate(client *cip.APIClient) *cobra.Command { + var ( + id string + name string + scope string + enabled bool + ) + cmd := &cobra.Command{ + Use: "update", + Short: "Update an existing dynamic parsing rule", + Run: func(cmd *cobra.Command, args []string) { + updateDynamicParsingRule(id, name, scope, enabled, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the dynamic parsing rule") + cmd.Flags().StringVar(&name, "name", "", "Specify the name of the dynamic parsing rule") + cmd.Flags().StringVar(&scope, "scope", "", "Scope of the dynamic parsing rule. "+ + "This could be a sourceCategory, sourceHost, or any other metadata that describes the data you want to extract from.") + cmd.Flags().BoolVar(&enabled, "enabled", true, "Set to false if you don't want to enable the rule") + cmd.MarkFlagRequired("id") + cmd.MarkFlagRequired("name") + cmd.MarkFlagRequired("scope") + return cmd +} + +func updateDynamicParsingRule(id string, name string, scope string, enabled bool, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.UpdateDynamicParsingRule(types.DynamicRuleDefinition{ + Name: name, + Scope: scope, + Enabled: enabled, + }, + id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/field-extraction-rules/create/create.go b/pkg/cmd/field-extraction-rules/create/create.go deleted file mode 100644 index fd8849b9..00000000 --- a/pkg/cmd/field-extraction-rules/create/create.go +++ /dev/null @@ -1,80 +0,0 @@ -package create - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdFieldExtractionRulesCreate() *cobra.Command { - var ( - name string - scope string - parseExpression string - enabled bool - ) - - cmd := &cobra.Command{ - Use: "create", - Short: "Create a new field extraction rule.", - Run: func(cmd *cobra.Command, args []string) { - createFieldExtractionRule(name, scope, parseExpression, enabled) - }, - } - cmd.Flags().StringVar(&name, "name", "", "Specify the name of the field extraction rule") - cmd.Flags().StringVar(&scope, "scope", "", "Scope of the field extraction rule. "+ - "This could be a sourceCategory, sourceHost, or any other metadata that describes the data you want to extract from.") - cmd.Flags().StringVar(&parseExpression, "parseExpression", "", "Specify the fields to be parsed") - cmd.Flags().BoolVar(&enabled, "enabled", true, "Set to false if you don't want to enable the rule") - cmd.MarkFlagRequired("name") - cmd.MarkFlagRequired("scope") - cmd.MarkFlagRequired("parseExpression") - return cmd -} - -func createFieldExtractionRule(name string, scope string, parseExpression string, enabled bool) { - var fieldExtractionRuleResponse api.FieldExtractionRules - log := logging.GetConsoleLogger() - requestBodySchema := &api.CreateFieldExtractionRule{ - Name: name, - Scope: scope, - ParseExpression: parseExpression, - Enabled: enabled, - } - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("error marshalling request body") - } - requestUrl := "/v1/extractionRules" - client, request := factory.NewHttpRequestWithBody("POST", requestUrl, requestBody) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &fieldExtractionRuleResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - fieldExtractionRuleResponseJson, err := json.MarshalIndent(fieldExtractionRuleResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal lookupTableResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(fieldExtractionRuleResponseJson)) - } -} diff --git a/pkg/cmd/field-extraction-rules/delete/delete.go b/pkg/cmd/field-extraction-rules/delete/delete.go deleted file mode 100644 index 6b5f4cd0..00000000 --- a/pkg/cmd/field-extraction-rules/delete/delete.go +++ /dev/null @@ -1,52 +0,0 @@ -package delete - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdFieldExtractionRulesDelete() *cobra.Command { - var id string - - cmd := &cobra.Command{ - Use: "delete", - Short: "Delete a field extraction rule with the given identifier.", - Run: func(cmd *cobra.Command, args []string) { - deleteFieldExtractionRules(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the field extraction rule") - cmd.MarkFlagRequired("id") - return cmd -} - -func deleteFieldExtractionRules(id string) { - log := logging.GetConsoleLogger() - requestUrl := "/v1/extractionRules/" + id - client, request := factory.NewHttpRequest("DELETE", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - if response.StatusCode != 204 { - var responseError api.ResponseError - err := json.Unmarshal(responseBody, &responseError) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - } else { - fmt.Println("Extraction rule was deleted successfully.") - } -} diff --git a/pkg/cmd/field-extraction-rules/get/get.go b/pkg/cmd/field-extraction-rules/get/get.go deleted file mode 100644 index e09ba3d8..00000000 --- a/pkg/cmd/field-extraction-rules/get/get.go +++ /dev/null @@ -1,59 +0,0 @@ -package get - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdFieldExtractionRulesGet() *cobra.Command { - var id string - - cmd := &cobra.Command{ - Use: "get", - Short: "Get a field extraction rule with the given identifier.", - Run: func(cmd *cobra.Command, args []string) { - getFieldExtractionRule(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the field extraction rule") - cmd.MarkFlagRequired("id") - return cmd -} - -func getFieldExtractionRule(id string) { - var fieldExtractionRulesResponse api.FieldExtractionRules - log := logging.GetConsoleLogger() - requestUrl := "/v1/extractionRules/" + id - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &fieldExtractionRulesResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - fieldExtractionRulesResponseJson, err := json.MarshalIndent(fieldExtractionRulesResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(fieldExtractionRulesResponseJson)) - } -} diff --git a/pkg/cmd/field-extraction-rules/list/list.go b/pkg/cmd/field-extraction-rules/list/list.go deleted file mode 100644 index 4784afec..00000000 --- a/pkg/cmd/field-extraction-rules/list/list.go +++ /dev/null @@ -1,65 +0,0 @@ -package list - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "net/url" - "strconv" -) - -func NewCmdFieldExtractionRulesList() *cobra.Command { - var ( - limit int - ) - - cmd := &cobra.Command{ - Use: "list", - Short: "Get a list of all field extraction rules.", - Run: func(cmd *cobra.Command, args []string) { - listFieldExtractionRules(limit) - }, - } - cmd.Flags().IntVar(&limit, "limit", 100, "Specify the number of results to return maximum is 1000") - return cmd -} - -func listFieldExtractionRules(limit int) { - var fieldExtractionRulesResponse api.ListFieldExtractionRules - log := logging.GetConsoleLogger() - requestUrl := "/v1/extractionRules" - client, request := factory.NewHttpRequest("GET", requestUrl) - query := url.Values{} - query.Add("limit", strconv.Itoa(limit)) - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &fieldExtractionRulesResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - fieldExtractionRulesResponseJson, err := json.MarshalIndent(fieldExtractionRulesResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(fieldExtractionRulesResponseJson)) - } -} diff --git a/pkg/cmd/field-extraction-rules/update/update.go b/pkg/cmd/field-extraction-rules/update/update.go deleted file mode 100644 index 67416db4..00000000 --- a/pkg/cmd/field-extraction-rules/update/update.go +++ /dev/null @@ -1,80 +0,0 @@ -package update - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdFieldExtractionRulesUpdate() *cobra.Command { - var ( - id string - name string - scope string - parseExpression string - enabled bool - ) - - cmd := &cobra.Command{ - Use: "update", - Short: "Update an existing field extraction rule.", - Run: func(cmd *cobra.Command, args []string) { - updateFieldExtractionRule(id, name, scope, parseExpression, enabled) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the field extraction rule") - cmd.Flags().StringVar(&name, "name", "", "Specify the name of the field extraction rule") - cmd.Flags().StringVar(&scope, "scope", "", "Scope of the field extraction rule. "+ - "This could be a sourceCategory, sourceHost, or any other metadata that describes the data you want to extract from.") - cmd.Flags().StringVar(&parseExpression, "parseExpression", "", "Specify the fields to be parsed") - cmd.Flags().BoolVar(&enabled, "enabled", true, "Set to false if you don't want to enable the rule") - cmd.MarkFlagRequired("id") - cmd.MarkFlagRequired("name") - cmd.MarkFlagRequired("scope") - cmd.MarkFlagRequired("parseExpression") - return cmd -} - -func updateFieldExtractionRule(id string, name string, scope string, parseExpression string, enabled bool) { - var fieldExtractionRulesResponse api.FieldExtractionRules - log := logging.GetConsoleLogger() - requestBodySchema := &api.CreateFieldExtractionRule{ - Name: name, - Scope: scope, - ParseExpression: parseExpression, - Enabled: enabled, - } - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("failed to marshal request body") - } - requestUrl := "/v1/extractionRules/" + id - client, request := factory.NewHttpRequestWithBody("PUT", requestUrl, requestBody) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("error reading response body from request") - } - err = json.Unmarshal(responseBody, &fieldExtractionRulesResponse) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - fieldExtractionRulesResponseJson, err := json.MarshalIndent(fieldExtractionRulesResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("error marshalling response body") - } - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(fieldExtractionRulesResponseJson)) - } -} diff --git a/pkg/cmd/field-management/create-field/create-field.go b/pkg/cmd/field-management/create-field/create-field.go deleted file mode 100644 index 49301703..00000000 --- a/pkg/cmd/field-management/create-field/create-field.go +++ /dev/null @@ -1,66 +0,0 @@ -package create_field - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdFieldManagementCreateField() *cobra.Command { - var fieldName string - - cmd := &cobra.Command{ - Use: "create-field", - Short: "Adding a field will define it in the Fields schema allowing it to be assigned as metadata to your logs.", - Run: func(cmd *cobra.Command, args []string) { - createField(fieldName) - }, - } - cmd.Flags().StringVar(&fieldName, "fieldName", "", "Specify the name of the field") - cmd.MarkFlagRequired("fieldName") - return cmd -} - -func createField(fieldName string) { - var fieldsResponse api.Fields - log := logging.GetConsoleLogger() - requestBodySchema := &api.CreateField{ - FieldName: fieldName, - } - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("error marshalling request body") - } - requestUrl := "/v1/fields" - client, request := factory.NewHttpRequestWithBody("POST", requestUrl, requestBody) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &fieldsResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - fieldsResponseJson, err := json.MarshalIndent(fieldsResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal lookupTableResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(fieldsResponseJson)) - } -} diff --git a/pkg/cmd/field-management/delete-field/delete-field.go b/pkg/cmd/field-management/delete-field/delete-field.go deleted file mode 100644 index cc9f7f77..00000000 --- a/pkg/cmd/field-management/delete-field/delete-field.go +++ /dev/null @@ -1,54 +0,0 @@ -package delete_field - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdFieldManagementDeleteField() *cobra.Command { - var id string - - cmd := &cobra.Command{ - Use: "delete-field", - Short: "Deleting a field does not delete historical data assigned with that field. " + - "If you delete a field by mistake and one or more of those dependencies break, you can re-add the field to get things working properly again. " + - "You should always disable a field using sumocli field-management disable-custom-field and ensure things are behaving as expected before deleting a field.", - Run: func(cmd *cobra.Command, args []string) { - deleteField(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the field") - cmd.MarkFlagRequired("id") - return cmd -} - -func deleteField(id string) { - log := logging.GetConsoleLogger() - requestUrl := "/v1/fields/" + id - client, request := factory.NewHttpRequest("DELETE", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - if response.StatusCode != 204 { - var responseError api.ResponseError - err := json.Unmarshal(responseBody, &responseError) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - } else { - fmt.Println("The field was successfully deleted.") - } -} diff --git a/pkg/cmd/field-management/disable-custom-field/disable-custom-field.go b/pkg/cmd/field-management/disable-custom-field/disable-custom-field.go deleted file mode 100644 index 07715d3f..00000000 --- a/pkg/cmd/field-management/disable-custom-field/disable-custom-field.go +++ /dev/null @@ -1,53 +0,0 @@ -package disable_custom_field - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdFieldManagementDisableCustomField() *cobra.Command { - var id string - - cmd := &cobra.Command{ - Use: "disable-custom-field", - Short: "After disabling a field Sumo Logic will start dropping its incoming values at ingest. " + - "As a result, they won't be searchable or usable. Historical values are not removed and remain searchable.", - Run: func(cmd *cobra.Command, args []string) { - disableCustomField(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the field") - cmd.MarkFlagRequired("id") - return cmd -} - -func disableCustomField(id string) { - log := logging.GetConsoleLogger() - requestUrl := "/v1/fields/" + id + "/disable" - client, request := factory.NewHttpRequest("DELETE", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - if response.StatusCode != 204 { - var responseError api.ResponseError - err := json.Unmarshal(responseBody, &responseError) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - } else { - fmt.Println("Field has been disabled.") - } -} diff --git a/pkg/cmd/field-management/enable-custom-field/enable-custom-field.go b/pkg/cmd/field-management/enable-custom-field/enable-custom-field.go deleted file mode 100644 index 4e2ba740..00000000 --- a/pkg/cmd/field-management/enable-custom-field/enable-custom-field.go +++ /dev/null @@ -1,54 +0,0 @@ -package enable_custom_field - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdFieldManagementEnableCustomField() *cobra.Command { - var id string - - cmd := &cobra.Command{ - Use: "enable-custom-field", - Short: "Fields have to be enabled to be assigned to your data. " + - "This operation ensures that a specified field is enabled and Sumo Logic will treat it as safe to process. " + - "All created custom fields using sumocli field-management create-field are enabled by default.", - Run: func(cmd *cobra.Command, args []string) { - enableCustomField(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the field") - cmd.MarkFlagRequired("id") - return cmd -} - -func enableCustomField(id string) { - log := logging.GetConsoleLogger() - requestUrl := "/v1/fields/" + id + "/enable" - client, request := factory.NewHttpRequest("PUT", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - if response.StatusCode != 204 { - var responseError api.ResponseError - err := json.Unmarshal(responseBody, &responseError) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - } else { - fmt.Println("Field has been enabled.") - } -} diff --git a/pkg/cmd/field-management/get-builtin-field/get-builtin-field.go b/pkg/cmd/field-management/get-builtin-field/get-builtin-field.go deleted file mode 100644 index 58d944a8..00000000 --- a/pkg/cmd/field-management/get-builtin-field/get-builtin-field.go +++ /dev/null @@ -1,59 +0,0 @@ -package get_builtin_field - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdFieldManagementGetBuiltinField() *cobra.Command { - var id string - - cmd := &cobra.Command{ - Use: "get-builtin-field", - Short: "Get the details of a built-in field.", - Run: func(cmd *cobra.Command, args []string) { - getBuiltinField(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the builtin field") - cmd.MarkFlagRequired("id") - return cmd -} - -func getBuiltinField(id string) { - var fieldsResponse api.Fields - log := logging.GetConsoleLogger() - requestUrl := "/v1/fields/builtin/" + id - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &fieldsResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - fieldsResponseJson, err := json.MarshalIndent(fieldsResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(fieldsResponseJson)) - } -} diff --git a/pkg/cmd/field-management/get-capacity-info/get-capacity-info.go b/pkg/cmd/field-management/get-capacity-info/get-capacity-info.go deleted file mode 100644 index 3d19d6d8..00000000 --- a/pkg/cmd/field-management/get-capacity-info/get-capacity-info.go +++ /dev/null @@ -1,56 +0,0 @@ -package get_capacity_info - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdFieldManagementGetCapacityInfo() *cobra.Command { - cmd := &cobra.Command{ - Use: "get-capacity-info", - Short: "Every account has a limited number of fields available." + - "This command returns your account limitations and remaining quota", - Run: func(cmd *cobra.Command, args []string) { - getCapacityInfo() - }, - } - return cmd -} - -func getCapacityInfo() { - var capacityResponse api.GetCapacityInformation - log := logging.GetConsoleLogger() - requestUrl := "/v1/fields/quota" - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &capacityResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - capacityResponseJson, err := json.MarshalIndent(capacityResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(capacityResponseJson)) - } -} diff --git a/pkg/cmd/field-management/get-custom-field/get-custom-field.go b/pkg/cmd/field-management/get-custom-field/get-custom-field.go deleted file mode 100644 index e148e4f8..00000000 --- a/pkg/cmd/field-management/get-custom-field/get-custom-field.go +++ /dev/null @@ -1,59 +0,0 @@ -package get_custom_field - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdFieldManagementGetCustomField() *cobra.Command { - var id string - - cmd := &cobra.Command{ - Use: "get-custom-field", - Short: "Get the details of a custom field.", - Run: func(cmd *cobra.Command, args []string) { - getCustomField(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the custom field") - cmd.MarkFlagRequired("id") - return cmd -} - -func getCustomField(id string) { - var fieldsResponse api.Fields - log := logging.GetConsoleLogger() - requestUrl := "/v1/fields/" + id - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &fieldsResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - fieldsResponseJson, err := json.MarshalIndent(fieldsResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(fieldsResponseJson)) - } -} diff --git a/pkg/cmd/field-management/list-builtin-fields/list-builtin-fields.go b/pkg/cmd/field-management/list-builtin-fields/list-builtin-fields.go deleted file mode 100644 index 4a951c1c..00000000 --- a/pkg/cmd/field-management/list-builtin-fields/list-builtin-fields.go +++ /dev/null @@ -1,56 +0,0 @@ -package list_builtin_fields - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdFieldManagementListBuiltinFields() *cobra.Command { - cmd := &cobra.Command{ - Use: "list-builtin-fields", - Short: "Built-in fields are created automatically by Sumo Logic for standard configuration purposes. " + - "They include _sourceHost and _sourceCategory. Built-in fields can't be deleted or disabled.", - Run: func(cmd *cobra.Command, args []string) { - listBuiltinFields() - }, - } - return cmd -} - -func listBuiltinFields() { - var fieldsResponse api.GetFields - log := logging.GetConsoleLogger() - requestUrl := "/v1/fields/builtin" - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &fieldsResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - fieldsResponseJson, err := json.MarshalIndent(fieldsResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(fieldsResponseJson)) - } -} diff --git a/pkg/cmd/field-management/list-custom-fields/list-custom-fields.go b/pkg/cmd/field-management/list-custom-fields/list-custom-fields.go deleted file mode 100644 index ed4c90c8..00000000 --- a/pkg/cmd/field-management/list-custom-fields/list-custom-fields.go +++ /dev/null @@ -1,55 +0,0 @@ -package list_custom_fields - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdFieldManagementListCustomFields() *cobra.Command { - cmd := &cobra.Command{ - Use: "list-custom-fields", - Short: "Request a list of all the custom fields configured in your account.", - Run: func(cmd *cobra.Command, args []string) { - listCustomFields() - }, - } - return cmd -} - -func listCustomFields() { - var fieldsResponse api.GetFields - log := logging.GetConsoleLogger() - requestUrl := "/v1/fields" - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &fieldsResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - fieldsResponseJson, err := json.MarshalIndent(fieldsResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(fieldsResponseJson)) - } -} diff --git a/pkg/cmd/field-management/list-dropped-fields/list-dropped-fields.go b/pkg/cmd/field-management/list-dropped-fields/list-dropped-fields.go deleted file mode 100644 index d06280ef..00000000 --- a/pkg/cmd/field-management/list-dropped-fields/list-dropped-fields.go +++ /dev/null @@ -1,56 +0,0 @@ -package list_dropped_fields - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdFieldManagementListDroppedFields() *cobra.Command { - cmd := &cobra.Command{ - Use: "list-dropped-fields", - Short: "Dropped fields are fields sent to Sumo Logic, but are ignored since they are not defined in your Fields schema. " + - "In order to save these values a field must both exist and be enabled.", - Run: func(cmd *cobra.Command, args []string) { - listDroppedFields() - }, - } - return cmd -} - -func listDroppedFields() { - var fieldsResponse api.GetDroppedFields - log := logging.GetConsoleLogger() - requestUrl := "/v1/fields/dropped" - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &fieldsResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - fieldsResponseJson, err := json.MarshalIndent(fieldsResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(fieldsResponseJson)) - } -} diff --git a/pkg/cmd/field_extraction_rules/create/create.go b/pkg/cmd/field_extraction_rules/create/create.go new file mode 100644 index 00000000..667d0ffe --- /dev/null +++ b/pkg/cmd/field_extraction_rules/create/create.go @@ -0,0 +1,47 @@ +package create + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdFieldExtractionRulesCreate(client *cip.APIClient) *cobra.Command { + var ( + name string + scope string + parseExpression string + enabled bool + ) + cmd := &cobra.Command{ + Use: "create", + Short: "Create a new field extraction rule.", + Run: func(cmd *cobra.Command, args []string) { + createFieldExtractionRule(name, scope, parseExpression, enabled, client) + }, + } + cmd.Flags().StringVar(&name, "name", "", "Specify the name of the field extraction rule") + cmd.Flags().StringVar(&scope, "scope", "", "Scope of the field extraction rule. "+ + "This could be a sourceCategory, sourceHost, or any other metadata that describes the data you want to extract from.") + cmd.Flags().StringVar(&parseExpression, "parseExpression", "", "Specify the fields to be parsed") + cmd.Flags().BoolVar(&enabled, "enabled", true, "Set to false if you don't want to enable the rule") + cmd.MarkFlagRequired("name") + cmd.MarkFlagRequired("scope") + cmd.MarkFlagRequired("parseExpression") + return cmd +} + +func createFieldExtractionRule(name string, scope string, parseExpression string, enabled bool, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.CreateExtractionRule(types.ExtractionRuleDefinition{ + Name: name, + Scope: scope, + ParseExpression: parseExpression, + Enabled: enabled, + }) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/field_extraction_rules/delete/delete.go b/pkg/cmd/field_extraction_rules/delete/delete.go new file mode 100644 index 00000000..27bf1f0c --- /dev/null +++ b/pkg/cmd/field_extraction_rules/delete/delete.go @@ -0,0 +1,30 @@ +package delete + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdFieldExtractionRulesDelete(client *cip.APIClient) *cobra.Command { + var id string + cmd := &cobra.Command{ + Use: "delete", + Short: "Delete a field extraction rule with the given identifier.", + Run: func(cmd *cobra.Command, args []string) { + deleteFieldExtractionRules(id, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the field extraction rule") + cmd.MarkFlagRequired("id") + return cmd +} + +func deleteFieldExtractionRules(id string, client *cip.APIClient) { + httpResponse, errorResponse := client.DeleteExtractionRule(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(nil, httpResponse, errorResponse, "Extraction rule was deleted successfully.") + } +} diff --git a/pkg/cmd/field-extraction-rules/field-extraction-rules.go b/pkg/cmd/field_extraction_rules/field-extraction-rules.go similarity index 69% rename from pkg/cmd/field-extraction-rules/field-extraction-rules.go rename to pkg/cmd/field_extraction_rules/field-extraction-rules.go index a3e2f8ca..0bf7c34a 100644 --- a/pkg/cmd/field-extraction-rules/field-extraction-rules.go +++ b/pkg/cmd/field_extraction_rules/field-extraction-rules.go @@ -2,23 +2,24 @@ package field_extraction_rules import ( "github.com/spf13/cobra" - NewCmdFieldExtractionRulesCreate "github.com/wizedkyle/sumocli/pkg/cmd/field-extraction-rules/create" - NewCmdFieldExtractionRulesDelete "github.com/wizedkyle/sumocli/pkg/cmd/field-extraction-rules/delete" - NewCmdFieldExtractionRulesGet "github.com/wizedkyle/sumocli/pkg/cmd/field-extraction-rules/get" - NewCmdFieldExtractionRulesList "github.com/wizedkyle/sumocli/pkg/cmd/field-extraction-rules/list" - NewCmdFieldExtractionRulesUpdate "github.com/wizedkyle/sumocli/pkg/cmd/field-extraction-rules/update" + NewCmdFieldExtractionRulesCreate "github.com/wizedkyle/sumocli/pkg/cmd/field_extraction_rules/create" + NewCmdFieldExtractionRulesDelete "github.com/wizedkyle/sumocli/pkg/cmd/field_extraction_rules/delete" + NewCmdFieldExtractionRulesGet "github.com/wizedkyle/sumocli/pkg/cmd/field_extraction_rules/get" + NewCmdFieldExtractionRulesList "github.com/wizedkyle/sumocli/pkg/cmd/field_extraction_rules/list" + NewCmdFieldExtractionRulesUpdate "github.com/wizedkyle/sumocli/pkg/cmd/field_extraction_rules/update" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdFieldExtractionRules() *cobra.Command { +func NewCmdFieldExtractionRules(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "field-extraction-rules", Short: "Manage field extraction rules", Long: "Field Extraction Rules allow you to parse fields from your log messages at the time the messages are ingested eliminating the need to parse fields in your query.", } - cmd.AddCommand(NewCmdFieldExtractionRulesCreate.NewCmdFieldExtractionRulesCreate()) - cmd.AddCommand(NewCmdFieldExtractionRulesDelete.NewCmdFieldExtractionRulesDelete()) - cmd.AddCommand(NewCmdFieldExtractionRulesGet.NewCmdFieldExtractionRulesGet()) - cmd.AddCommand(NewCmdFieldExtractionRulesList.NewCmdFieldExtractionRulesList()) - cmd.AddCommand(NewCmdFieldExtractionRulesUpdate.NewCmdFieldExtractionRulesUpdate()) + cmd.AddCommand(NewCmdFieldExtractionRulesCreate.NewCmdFieldExtractionRulesCreate(client)) + cmd.AddCommand(NewCmdFieldExtractionRulesDelete.NewCmdFieldExtractionRulesDelete(client)) + cmd.AddCommand(NewCmdFieldExtractionRulesGet.NewCmdFieldExtractionRulesGet(client)) + cmd.AddCommand(NewCmdFieldExtractionRulesList.NewCmdFieldExtractionRulesList(client)) + cmd.AddCommand(NewCmdFieldExtractionRulesUpdate.NewCmdFieldExtractionRulesUpdate(client)) return cmd } diff --git a/pkg/cmd/field_extraction_rules/get/get.go b/pkg/cmd/field_extraction_rules/get/get.go new file mode 100644 index 00000000..1c65e582 --- /dev/null +++ b/pkg/cmd/field_extraction_rules/get/get.go @@ -0,0 +1,30 @@ +package get + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdFieldExtractionRulesGet(client *cip.APIClient) *cobra.Command { + var id string + cmd := &cobra.Command{ + Use: "get", + Short: "Get a field extraction rule with the given identifier.", + Run: func(cmd *cobra.Command, args []string) { + getFieldExtractionRule(id, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the field extraction rule") + cmd.MarkFlagRequired("id") + return cmd +} + +func getFieldExtractionRule(id string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.GetExtractionRule(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/field_extraction_rules/list/list.go b/pkg/cmd/field_extraction_rules/list/list.go new file mode 100644 index 00000000..04d7f7d5 --- /dev/null +++ b/pkg/cmd/field_extraction_rules/list/list.go @@ -0,0 +1,50 @@ +package list + +import ( + "github.com/antihax/optional" + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdFieldExtractionRulesList(client *cip.APIClient) *cobra.Command { + var limit int32 + cmd := &cobra.Command{ + Use: "list", + Short: "Get a list of all field extraction rules.", + Run: func(cmd *cobra.Command, args []string) { + listFieldExtractionRules(limit, client) + }, + } + cmd.Flags().Int32Var(&limit, "limit", 100, "Specify the number of results to return maximum is 1000") + return cmd +} + +func listFieldExtractionRules(limit int32, client *cip.APIClient) { + var options types.ExtractionRuleOpts + var paginationToken string + options.Limit = optional.NewInt32(limit) + apiResponse, httpResponse, errorResponse := client.ListExtractionRules(&options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + paginationToken = apiResponse.Next + for paginationToken != "" { + apiResponse = listFieldExtractionRulesPagination(client, options, paginationToken) + paginationToken = apiResponse.Next + } +} + +func listFieldExtractionRulesPagination(client *cip.APIClient, options types.ExtractionRuleOpts, token string) types.ListExtractionRulesResponse { + options.Token = optional.NewString(token) + apiResponse, httpResponse, errorResponse := client.ListExtractionRules(&options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + return apiResponse +} diff --git a/pkg/cmd/field_extraction_rules/update/update.go b/pkg/cmd/field_extraction_rules/update/update.go new file mode 100644 index 00000000..546cda2f --- /dev/null +++ b/pkg/cmd/field_extraction_rules/update/update.go @@ -0,0 +1,51 @@ +package update + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdFieldExtractionRulesUpdate(client *cip.APIClient) *cobra.Command { + var ( + id string + name string + scope string + parseExpression string + enabled bool + ) + cmd := &cobra.Command{ + Use: "update", + Short: "Update an existing field extraction rule.", + Run: func(cmd *cobra.Command, args []string) { + updateFieldExtractionRule(id, name, scope, parseExpression, enabled, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the field extraction rule") + cmd.Flags().StringVar(&name, "name", "", "Specify the name of the field extraction rule") + cmd.Flags().StringVar(&scope, "scope", "", "Scope of the field extraction rule. "+ + "This could be a sourceCategory, sourceHost, or any other metadata that describes the data you want to extract from.") + cmd.Flags().StringVar(&parseExpression, "parseExpression", "", "Specify the fields to be parsed") + cmd.Flags().BoolVar(&enabled, "enabled", true, "Set to false if you don't want to enable the rule") + cmd.MarkFlagRequired("id") + cmd.MarkFlagRequired("name") + cmd.MarkFlagRequired("scope") + cmd.MarkFlagRequired("parseExpression") + return cmd +} + +func updateFieldExtractionRule(id string, name string, scope string, parseExpression string, enabled bool, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.UpdateExtractionRule(types.UpdateExtractionRuleDefinition{ + Name: name, + Scope: scope, + ParseExpression: parseExpression, + Enabled: enabled, + }, + id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/field_management/create_field/create_field.go b/pkg/cmd/field_management/create_field/create_field.go new file mode 100644 index 00000000..edd3b208 --- /dev/null +++ b/pkg/cmd/field_management/create_field/create_field.go @@ -0,0 +1,33 @@ +package create_field + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdFieldManagementCreateField(client *cip.APIClient) *cobra.Command { + var fieldName string + cmd := &cobra.Command{ + Use: "create-field", + Short: "Adding a field will define it in the Fields schema allowing it to be assigned as metadata to your logs.", + Run: func(cmd *cobra.Command, args []string) { + createField(fieldName, client) + }, + } + cmd.Flags().StringVar(&fieldName, "fieldName", "", "Specify the name of the field") + cmd.MarkFlagRequired("fieldName") + return cmd +} + +func createField(fieldName string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.CreateField(types.FieldName{ + FieldName: fieldName, + }) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/field_management/delete_field/delete_field.go b/pkg/cmd/field_management/delete_field/delete_field.go new file mode 100644 index 00000000..e9286b10 --- /dev/null +++ b/pkg/cmd/field_management/delete_field/delete_field.go @@ -0,0 +1,32 @@ +package delete_field + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdFieldManagementDeleteField(client *cip.APIClient) *cobra.Command { + var id string + cmd := &cobra.Command{ + Use: "delete-field", + Short: "Deleting a field does not delete historical data assigned with that field. " + + "If you delete a field by mistake and one or more of those dependencies break, you can re-add the field to get things working properly again. " + + "You should always disable a field using sumocli field_management disable_custom_field and ensure things are behaving as expected before deleting a field.", + Run: func(cmd *cobra.Command, args []string) { + deleteField(id, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the field") + cmd.MarkFlagRequired("id") + return cmd +} + +func deleteField(id string, client *cip.APIClient) { + httpResponse, errorResponse := client.DeleteField(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(nil, httpResponse, errorResponse, "The field was successfully deleted.") + } +} diff --git a/pkg/cmd/field_management/disable_custom_field/disable_custom_field.go b/pkg/cmd/field_management/disable_custom_field/disable_custom_field.go new file mode 100644 index 00000000..10a5d780 --- /dev/null +++ b/pkg/cmd/field_management/disable_custom_field/disable_custom_field.go @@ -0,0 +1,31 @@ +package disable_custom_field + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdFieldManagementDisableCustomField(client *cip.APIClient) *cobra.Command { + var id string + cmd := &cobra.Command{ + Use: "disable-custom-field", + Short: "After disabling a field Sumo Logic will start dropping its incoming values at ingest. " + + "As a result, they won't be searchable or usable. Historical values are not removed and remain searchable.", + Run: func(cmd *cobra.Command, args []string) { + disableCustomField(id, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the field") + cmd.MarkFlagRequired("id") + return cmd +} + +func disableCustomField(id string, client *cip.APIClient) { + httpResponse, errorResponse := client.DisableField(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(nil, httpResponse, errorResponse, "Field has been disabled.") + } +} diff --git a/pkg/cmd/field_management/enable_custom_field/enable_custom_field.go b/pkg/cmd/field_management/enable_custom_field/enable_custom_field.go new file mode 100644 index 00000000..cc2a88fa --- /dev/null +++ b/pkg/cmd/field_management/enable_custom_field/enable_custom_field.go @@ -0,0 +1,32 @@ +package enable_custom_field + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdFieldManagementEnableCustomField(client *cip.APIClient) *cobra.Command { + var id string + cmd := &cobra.Command{ + Use: "enable-custom-field", + Short: "Fields have to be enabled to be assigned to your data. " + + "This operation ensures that a specified field is enabled and Sumo Logic will treat it as safe to process. " + + "All created custom fields using sumocli field_management create_field are enabled by default.", + Run: func(cmd *cobra.Command, args []string) { + enableCustomField(id, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the field") + cmd.MarkFlagRequired("id") + return cmd +} + +func enableCustomField(id string, client *cip.APIClient) { + httpResponse, errorResponse := client.EnableField(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(nil, httpResponse, errorResponse, "Field has been enabled.") + } +} diff --git a/pkg/cmd/field-management/field-management.go b/pkg/cmd/field_management/field-management.go similarity index 64% rename from pkg/cmd/field-management/field-management.go rename to pkg/cmd/field_management/field-management.go index 73101cf6..9f17461b 100644 --- a/pkg/cmd/field-management/field-management.go +++ b/pkg/cmd/field_management/field-management.go @@ -2,19 +2,20 @@ package field_management import ( "github.com/spf13/cobra" - NewCmdFieldManagementCreateField "github.com/wizedkyle/sumocli/pkg/cmd/field-management/create-field" - NewCmdFieldManagementDeleteField "github.com/wizedkyle/sumocli/pkg/cmd/field-management/delete-field" - NewCmdFieldManagementDisableCustomField "github.com/wizedkyle/sumocli/pkg/cmd/field-management/disable-custom-field" - NewCmdFieldManagementEnableCustomField "github.com/wizedkyle/sumocli/pkg/cmd/field-management/enable-custom-field" - NewCmdFieldManagementGetBuiltinField "github.com/wizedkyle/sumocli/pkg/cmd/field-management/get-builtin-field" - NewCmdFieldManagementGetCapacityInfo "github.com/wizedkyle/sumocli/pkg/cmd/field-management/get-capacity-info" - NewCmdFieldManagementGetCustomField "github.com/wizedkyle/sumocli/pkg/cmd/field-management/get-custom-field" - NewCmdFieldManagementListBuiltinFields "github.com/wizedkyle/sumocli/pkg/cmd/field-management/list-builtin-fields" - NewCmdFieldManagementListCustomFields "github.com/wizedkyle/sumocli/pkg/cmd/field-management/list-custom-fields" - NewCmdFieldManagementListDroppedFields "github.com/wizedkyle/sumocli/pkg/cmd/field-management/list-dropped-fields" + NewCmdFieldManagementCreateField "github.com/wizedkyle/sumocli/pkg/cmd/field_management/create_field" + NewCmdFieldManagementDeleteField "github.com/wizedkyle/sumocli/pkg/cmd/field_management/delete_field" + NewCmdFieldManagementDisableCustomField "github.com/wizedkyle/sumocli/pkg/cmd/field_management/disable_custom_field" + NewCmdFieldManagementEnableCustomField "github.com/wizedkyle/sumocli/pkg/cmd/field_management/enable_custom_field" + NewCmdFieldManagementGetBuiltinField "github.com/wizedkyle/sumocli/pkg/cmd/field_management/get_builtin_field" + NewCmdFieldManagementGetCapacityInfo "github.com/wizedkyle/sumocli/pkg/cmd/field_management/get_capacity_info" + NewCmdFieldManagementGetCustomField "github.com/wizedkyle/sumocli/pkg/cmd/field_management/get_custom_field" + NewCmdFieldManagementListBuiltinFields "github.com/wizedkyle/sumocli/pkg/cmd/field_management/list_builtin_fields" + NewCmdFieldManagementListCustomFields "github.com/wizedkyle/sumocli/pkg/cmd/field_management/list_custom_fields" + NewCmdFieldManagementListDroppedFields "github.com/wizedkyle/sumocli/pkg/cmd/field_management/list_dropped_fields" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdFieldManagement() *cobra.Command { +func NewCmdFieldManagement(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "field-management", Short: "Manage fields", @@ -22,15 +23,15 @@ func NewCmdFieldManagement() *cobra.Command { "They act as metadata tags that are assigned to your logs so you can search with them. " + "Each field contains a key-value pair, where the field name is the key. Fields may be referred to as Log Metadata Fields.", } - cmd.AddCommand(NewCmdFieldManagementCreateField.NewCmdFieldManagementCreateField()) - cmd.AddCommand(NewCmdFieldManagementDeleteField.NewCmdFieldManagementDeleteField()) - cmd.AddCommand(NewCmdFieldManagementDisableCustomField.NewCmdFieldManagementDisableCustomField()) - cmd.AddCommand(NewCmdFieldManagementEnableCustomField.NewCmdFieldManagementEnableCustomField()) - cmd.AddCommand(NewCmdFieldManagementGetBuiltinField.NewCmdFieldManagementGetBuiltinField()) - cmd.AddCommand(NewCmdFieldManagementGetCapacityInfo.NewCmdFieldManagementGetCapacityInfo()) - cmd.AddCommand(NewCmdFieldManagementGetCustomField.NewCmdFieldManagementGetCustomField()) - cmd.AddCommand(NewCmdFieldManagementListBuiltinFields.NewCmdFieldManagementListBuiltinFields()) - cmd.AddCommand(NewCmdFieldManagementListCustomFields.NewCmdFieldManagementListCustomFields()) - cmd.AddCommand(NewCmdFieldManagementListDroppedFields.NewCmdFieldManagementListDroppedFields()) + cmd.AddCommand(NewCmdFieldManagementCreateField.NewCmdFieldManagementCreateField(client)) + cmd.AddCommand(NewCmdFieldManagementDeleteField.NewCmdFieldManagementDeleteField(client)) + cmd.AddCommand(NewCmdFieldManagementDisableCustomField.NewCmdFieldManagementDisableCustomField(client)) + cmd.AddCommand(NewCmdFieldManagementEnableCustomField.NewCmdFieldManagementEnableCustomField(client)) + cmd.AddCommand(NewCmdFieldManagementGetBuiltinField.NewCmdFieldManagementGetBuiltinField(client)) + cmd.AddCommand(NewCmdFieldManagementGetCapacityInfo.NewCmdFieldManagementGetCapacityInfo(client)) + cmd.AddCommand(NewCmdFieldManagementGetCustomField.NewCmdFieldManagementGetCustomField(client)) + cmd.AddCommand(NewCmdFieldManagementListBuiltinFields.NewCmdFieldManagementListBuiltinFields(client)) + cmd.AddCommand(NewCmdFieldManagementListCustomFields.NewCmdFieldManagementListCustomFields(client)) + cmd.AddCommand(NewCmdFieldManagementListDroppedFields.NewCmdFieldManagementListDroppedFields(client)) return cmd } diff --git a/pkg/cmd/field_management/get_builtin_field/get_builtin_field.go b/pkg/cmd/field_management/get_builtin_field/get_builtin_field.go new file mode 100644 index 00000000..33233828 --- /dev/null +++ b/pkg/cmd/field_management/get_builtin_field/get_builtin_field.go @@ -0,0 +1,30 @@ +package get_builtin_field + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdFieldManagementGetBuiltinField(client *cip.APIClient) *cobra.Command { + var id string + cmd := &cobra.Command{ + Use: "get-builtin-field", + Short: "Get the details of a built-in field.", + Run: func(cmd *cobra.Command, args []string) { + getBuiltinField(id, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the builtin field") + cmd.MarkFlagRequired("id") + return cmd +} + +func getBuiltinField(id string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.GetBuiltInField(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/field_management/get_capacity_info/get_capacity_info.go b/pkg/cmd/field_management/get_capacity_info/get_capacity_info.go new file mode 100644 index 00000000..dfb3b7e8 --- /dev/null +++ b/pkg/cmd/field_management/get_capacity_info/get_capacity_info.go @@ -0,0 +1,28 @@ +package get_capacity_info + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdFieldManagementGetCapacityInfo(client *cip.APIClient) *cobra.Command { + cmd := &cobra.Command{ + Use: "get-capacity-info", + Short: "Every account has a limited number of fields available." + + "This command returns your account limitations and remaining quota", + Run: func(cmd *cobra.Command, args []string) { + getCapacityInfo(client) + }, + } + return cmd +} + +func getCapacityInfo(client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.GetFieldQuota() + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/field_management/get_custom_field/get_custom_field.go b/pkg/cmd/field_management/get_custom_field/get_custom_field.go new file mode 100644 index 00000000..4d569441 --- /dev/null +++ b/pkg/cmd/field_management/get_custom_field/get_custom_field.go @@ -0,0 +1,30 @@ +package get_custom_field + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdFieldManagementGetCustomField(client *cip.APIClient) *cobra.Command { + var id string + cmd := &cobra.Command{ + Use: "get-custom-field", + Short: "Get the details of a custom field.", + Run: func(cmd *cobra.Command, args []string) { + getCustomField(id, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the custom field") + cmd.MarkFlagRequired("id") + return cmd +} + +func getCustomField(id string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.GetCustomField(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/field_management/list_builtin_fields/list-builtin-fields.go b/pkg/cmd/field_management/list_builtin_fields/list-builtin-fields.go new file mode 100644 index 00000000..74af2818 --- /dev/null +++ b/pkg/cmd/field_management/list_builtin_fields/list-builtin-fields.go @@ -0,0 +1,28 @@ +package list_builtin_fields + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdFieldManagementListBuiltinFields(client *cip.APIClient) *cobra.Command { + cmd := &cobra.Command{ + Use: "list-builtin-fields", + Short: "Built-in fields are created automatically by Sumo Logic for standard configuration purposes. " + + "They include _sourceHost and _sourceCategory. Built-in fields can't be deleted or disabled.", + Run: func(cmd *cobra.Command, args []string) { + listBuiltinFields(client) + }, + } + return cmd +} + +func listBuiltinFields(client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.ListBuiltInFields() + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/field_management/list_custom_fields/list_custom_fields.go b/pkg/cmd/field_management/list_custom_fields/list_custom_fields.go new file mode 100644 index 00000000..efbadd2a --- /dev/null +++ b/pkg/cmd/field_management/list_custom_fields/list_custom_fields.go @@ -0,0 +1,27 @@ +package list_custom_fields + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdFieldManagementListCustomFields(client *cip.APIClient) *cobra.Command { + cmd := &cobra.Command{ + Use: "list-custom-fields", + Short: "Request a list of all the custom fields configured in your account.", + Run: func(cmd *cobra.Command, args []string) { + listCustomFields(client) + }, + } + return cmd +} + +func listCustomFields(client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.ListCustomFields() + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/field_management/list_dropped_fields/list_dropped_fields.go b/pkg/cmd/field_management/list_dropped_fields/list_dropped_fields.go new file mode 100644 index 00000000..9022d230 --- /dev/null +++ b/pkg/cmd/field_management/list_dropped_fields/list_dropped_fields.go @@ -0,0 +1,28 @@ +package list_dropped_fields + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdFieldManagementListDroppedFields(client *cip.APIClient) *cobra.Command { + cmd := &cobra.Command{ + Use: "list-dropped-fields", + Short: "Dropped fields are fields sent to Sumo Logic, but are ignored since they are not defined in your Fields schema. " + + "In order to save these values a field must both exist and be enabled.", + Run: func(cmd *cobra.Command, args []string) { + listDroppedFields(client) + }, + } + return cmd +} + +func listDroppedFields(client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.ListDroppedFields() + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/folders/create/create.go b/pkg/cmd/folders/create/create.go index 1ef9b7f9..c0612eb7 100644 --- a/pkg/cmd/folders/create/create.go +++ b/pkg/cmd/folders/create/create.go @@ -2,14 +2,13 @@ package create import ( "github.com/antihax/optional" - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdCreate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdCreate(client *cip.APIClient) *cobra.Command { var ( name string description string @@ -20,7 +19,7 @@ func NewCmdCreate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { Use: "create", Short: "Creates a new folder under the given parent folder.", Run: func(cmd *cobra.Command, args []string) { - create(name, description, parentId, isAdminMode, client, log) + create(name, description, parentId, isAdminMode, client) }, } cmd.Flags().StringVar(&name, "name", "", "Specify a name for the folder") @@ -32,18 +31,18 @@ func NewCmdCreate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { return cmd } -func create(name string, description string, parentId string, isAdminMode bool, client *cip.APIClient, log *zerolog.Logger) { +func create(name string, description string, parentId string, isAdminMode bool, client *cip.APIClient) { adminMode := cmdutils.AdminMode(isAdminMode) apiResponse, httpResponse, errorResponse := client.CreateFolder(types.FolderDefinition{ Name: name, Description: description, ParentId: parentId, }, - &types.FolderManagementApiCreateFolderOpts{ + &types.FolderOpts{ IsAdminMode: optional.NewString(adminMode), }) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to create folder") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/folders/folders.go b/pkg/cmd/folders/folders.go index 87061a81..b301900f 100644 --- a/pkg/cmd/folders/folders.go +++ b/pkg/cmd/folders/folders.go @@ -1,7 +1,6 @@ package folders import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" cmdFoldersCreate "github.com/wizedkyle/sumocli/pkg/cmd/folders/create" cmdFoldersGet "github.com/wizedkyle/sumocli/pkg/cmd/folders/get" @@ -16,21 +15,21 @@ import ( "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdFolders(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdFolders(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "folders ", Short: "Manage folders", Long: "Commands that allow you to manage content in your Sumo Logic tenant", } - cmd.AddCommand(cmdFoldersAdminRecommendedFolder.NewCmdGetAdminRecommendedFolder(client, log)) - cmd.AddCommand(cmdFoldersAdminRecommendedFolderResult.NewCmdGetAdminRecommendedFolderResult(client, log)) - cmd.AddCommand(cmdFoldersAdminRecommendedFolderStatus.NewCmdGetAdminRecommendedFolderStatus(client, log)) - cmd.AddCommand(cmdFoldersCreate.NewCmdCreate(client, log)) - cmd.AddCommand(cmdFoldersGet.NewCmdGet(client, log)) - cmd.AddCommand(cmdFoldersGlobalFolder.NewCmdGetGlobalFolder(client, log)) - cmd.AddCommand(cmdFoldersGlobalFolderResult.NewCmdGetGlobalFolderResult(client, log)) - cmd.AddCommand(cmdFoldersGlobalFolderStatus.NewCmdGetGlobalFolderStatus(client, log)) - cmd.AddCommand(cmdFoldersPersonalFolder.NewCmdGetPersonalFolder(client, log)) - cmd.AddCommand(cmdFoldersUpdate.NewCmdUpdate(client, log)) + cmd.AddCommand(cmdFoldersAdminRecommendedFolder.NewCmdGetAdminRecommendedFolder(client)) + cmd.AddCommand(cmdFoldersAdminRecommendedFolderResult.NewCmdGetAdminRecommendedFolderResult(client)) + cmd.AddCommand(cmdFoldersAdminRecommendedFolderStatus.NewCmdGetAdminRecommendedFolderStatus(client)) + cmd.AddCommand(cmdFoldersCreate.NewCmdCreate(client)) + cmd.AddCommand(cmdFoldersGet.NewCmdGet(client)) + cmd.AddCommand(cmdFoldersGlobalFolder.NewCmdGetGlobalFolder(client)) + cmd.AddCommand(cmdFoldersGlobalFolderResult.NewCmdGetGlobalFolderResult(client)) + cmd.AddCommand(cmdFoldersGlobalFolderStatus.NewCmdGetGlobalFolderStatus(client)) + cmd.AddCommand(cmdFoldersPersonalFolder.NewCmdGetPersonalFolder(client)) + cmd.AddCommand(cmdFoldersUpdate.NewCmdUpdate(client)) return cmd } diff --git a/pkg/cmd/folders/get/get.go b/pkg/cmd/folders/get/get.go index 3f1faa3d..742833ce 100644 --- a/pkg/cmd/folders/get/get.go +++ b/pkg/cmd/folders/get/get.go @@ -2,14 +2,13 @@ package get import ( "github.com/antihax/optional" - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdGet(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdGet(client *cip.APIClient) *cobra.Command { var ( id string isAdminMode bool @@ -18,7 +17,7 @@ func NewCmdGet(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { Use: "get", Short: "Get a folder with the given identifier.", Run: func(cmd *cobra.Command, args []string) { - get(id, isAdminMode, client, log) + get(id, isAdminMode, client) }, } cmd.Flags().StringVar(&id, "id", "", "Specify the identifier of the folder") @@ -27,13 +26,13 @@ func NewCmdGet(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { return cmd } -func get(id string, isAdminMode bool, client *cip.APIClient, log *zerolog.Logger) { +func get(id string, isAdminMode bool, client *cip.APIClient) { adminMode := cmdutils.AdminMode(isAdminMode) - apiResponse, httpResponse, errorResponse := client.GetFolder(id, &types.FolderManagementApiGetFolderOpts{ + apiResponse, httpResponse, errorResponse := client.GetFolder(id, &types.FolderOpts{ IsAdminMode: optional.NewString(adminMode), }) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to get folder") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/folders/get_admin_recommended_folder/get_admin_recommended_folder.go b/pkg/cmd/folders/get_admin_recommended_folder/get_admin_recommended_folder.go index 43c2f0aa..45584eee 100644 --- a/pkg/cmd/folders/get_admin_recommended_folder/get_admin_recommended_folder.go +++ b/pkg/cmd/folders/get_admin_recommended_folder/get_admin_recommended_folder.go @@ -2,34 +2,33 @@ package get_admin_recommended_folder import ( "github.com/antihax/optional" - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdGetAdminRecommendedFolder(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdGetAdminRecommendedFolder(client *cip.APIClient) *cobra.Command { var isAdminMode bool cmd := &cobra.Command{ Use: "get-admin-recommended-folder", Short: "Schedule an asynchronous job to get the top-level Admin Recommended content items.", Run: func(cmd *cobra.Command, args []string) { - getAdminRecommendedFolder(isAdminMode, client, log) + getAdminRecommendedFolder(isAdminMode, client) }, } cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "Set to true if you want to perform the request as a content administrator") return cmd } -func getAdminRecommendedFolder(isAdminMode bool, client *cip.APIClient, log *zerolog.Logger) { +func getAdminRecommendedFolder(isAdminMode bool, client *cip.APIClient) { adminMode := cmdutils.AdminMode(isAdminMode) - apiResponse, httpResponse, errorResponse := client.GetAdminRecommendedFolderAsync(&types.FolderManagementApiGetAdminRecommendedFolderAsyncOpts{ + apiResponse, httpResponse, errorResponse := client.GetAdminRecommendedFolderAsync(&types.FolderOpts{ IsAdminMode: optional.NewString(adminMode), }) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to create admin folder async job") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/folders/get_admin_recommended_folder_result/get_admin_recommended_folder_result.go b/pkg/cmd/folders/get_admin_recommended_folder_result/get_admin_recommended_folder_result.go index 1e42f2d6..7060e33c 100644 --- a/pkg/cmd/folders/get_admin_recommended_folder_result/get_admin_recommended_folder_result.go +++ b/pkg/cmd/folders/get_admin_recommended_folder_result/get_admin_recommended_folder_result.go @@ -1,20 +1,19 @@ package get_admin_recommended_folder_result import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdGetAdminRecommendedFolderResult(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdGetAdminRecommendedFolderResult(client *cip.APIClient) *cobra.Command { var jobId string cmd := &cobra.Command{ Use: "get-admin-recommended-folder-result", Short: "Get results from Admin Recommended job for the given job identifier.", Run: func(cmd *cobra.Command, args []string) { - getAdminRecommendedFolderResult(jobId, client, log) + getAdminRecommendedFolderResult(jobId, client) }, } cmd.Flags().StringVar(&jobId, "jobId", "", "Specify the job id (returned from running sumocli admin-recommended-folder)") @@ -22,10 +21,10 @@ func NewCmdGetAdminRecommendedFolderResult(client *cip.APIClient, log *zerolog.L return cmd } -func getAdminRecommendedFolderResult(jobId string, client *cip.APIClient, log *zerolog.Logger) { +func getAdminRecommendedFolderResult(jobId string, client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.GetAdminRecommendedFolderAsyncResult(jobId) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to get result of admin folder async job") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/folders/get_admin_recommended_folder_status/get_admin_recommended_folder_status.go b/pkg/cmd/folders/get_admin_recommended_folder_status/get_admin_recommended_folder_status.go index e6473dfd..c10ada62 100644 --- a/pkg/cmd/folders/get_admin_recommended_folder_status/get_admin_recommended_folder_status.go +++ b/pkg/cmd/folders/get_admin_recommended_folder_status/get_admin_recommended_folder_status.go @@ -1,20 +1,19 @@ package get_admin_recommended_folder_status import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdGetAdminRecommendedFolderStatus(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdGetAdminRecommendedFolderStatus(client *cip.APIClient) *cobra.Command { var jobId string cmd := &cobra.Command{ Use: "get-admin-recommended-folder-status", Short: "Get the status of an asynchronous Admin Recommended folder job for the given job identifier.", Run: func(cmd *cobra.Command, args []string) { - getAdminRecommendedFolderStatus(jobId, client, log) + getAdminRecommendedFolderStatus(jobId, client) }, } cmd.Flags().StringVar(&jobId, "jobId", "", "Specify the job id (returned from running sumocli admin-recommended-folder)") @@ -22,10 +21,10 @@ func NewCmdGetAdminRecommendedFolderStatus(client *cip.APIClient, log *zerolog.L return cmd } -func getAdminRecommendedFolderStatus(jobId string, client *cip.APIClient, log *zerolog.Logger) { +func getAdminRecommendedFolderStatus(jobId string, client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.GetAdminRecommendedFolderAsyncStatus(jobId) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to get admin folder async job status") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/folders/get_global_folder/get_global_folder.go b/pkg/cmd/folders/get_global_folder/get_global_folder.go index bffd6367..af64de62 100644 --- a/pkg/cmd/folders/get_global_folder/get_global_folder.go +++ b/pkg/cmd/folders/get_global_folder/get_global_folder.go @@ -2,14 +2,13 @@ package get_global_folder import ( "github.com/antihax/optional" - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdGetGlobalFolder(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdGetGlobalFolder(client *cip.APIClient) *cobra.Command { var isAdminMode bool cmd := &cobra.Command{ @@ -17,20 +16,20 @@ func NewCmdGetGlobalFolder(client *cip.APIClient, log *zerolog.Logger) *cobra.Co Short: "Schedule an asynchronous job to get global folder. " + "Global folder contains all content items that a user has permissions to view in the organization.", Run: func(cmd *cobra.Command, args []string) { - getGlobalFolder(isAdminMode, client, log) + getGlobalFolder(isAdminMode, client) }, } cmd.Flags().BoolVar(&isAdminMode, "isAdminMode", false, "Set to true if you want to perform the request as a content administrator") return cmd } -func getGlobalFolder(isAdminMode bool, client *cip.APIClient, log *zerolog.Logger) { +func getGlobalFolder(isAdminMode bool, client *cip.APIClient) { adminMode := cmdutils.AdminMode(isAdminMode) - apiResponse, httpResponse, errorResponse := client.GetGlobalFolderAsync(&types.FolderManagementApiGetGlobalFolderAsyncOpts{ + apiResponse, httpResponse, errorResponse := client.GetGlobalFolderAsync(&types.FolderOpts{ IsAdminMode: optional.NewString(adminMode), }) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to crate global folder async job") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/folders/get_global_folder_result/get_global_folder_result.go b/pkg/cmd/folders/get_global_folder_result/get_global_folder_result.go index 0e1fb022..6c3b6966 100644 --- a/pkg/cmd/folders/get_global_folder_result/get_global_folder_result.go +++ b/pkg/cmd/folders/get_global_folder_result/get_global_folder_result.go @@ -1,20 +1,19 @@ package get_global_folder_result import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdGetGlobalFolderResult(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdGetGlobalFolderResult(client *cip.APIClient) *cobra.Command { var jobId string cmd := &cobra.Command{ Use: "get-global-folder-result", Short: "Get results from global folder job for the given job identifier.", Run: func(cmd *cobra.Command, args []string) { - getGlobalFolderResult(jobId, client, log) + getGlobalFolderResult(jobId, client) }, } cmd.Flags().StringVar(&jobId, "jobId", "", "Specify the job id for the global folder (returned from running sumocli folders global-folder") @@ -22,10 +21,10 @@ func NewCmdGetGlobalFolderResult(client *cip.APIClient, log *zerolog.Logger) *co return cmd } -func getGlobalFolderResult(jobId string, client *cip.APIClient, log *zerolog.Logger) { +func getGlobalFolderResult(jobId string, client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.GetGlobalFolderAsyncResult(jobId) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to get global folder async job result") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/folders/get_global_folder_status/get_global_folder_status.go b/pkg/cmd/folders/get_global_folder_status/get_global_folder_status.go index 7e4d08c9..82dc62c3 100644 --- a/pkg/cmd/folders/get_global_folder_status/get_global_folder_status.go +++ b/pkg/cmd/folders/get_global_folder_status/get_global_folder_status.go @@ -1,20 +1,19 @@ package get_global_folder_status import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdGetGlobalFolderStatus(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdGetGlobalFolderStatus(client *cip.APIClient) *cobra.Command { var jobId string cmd := &cobra.Command{ Use: "get-global-folder-status", Short: "Get the status of an asynchronous global folder job for the given job identifier.", Run: func(cmd *cobra.Command, args []string) { - getGlobalFolderStatus(jobId, client, log) + getGlobalFolderStatus(jobId, client) }, } cmd.Flags().StringVar(&jobId, "jobId", "", "Specify the job id for the global folder (returned from running sumocli folders global-folder") @@ -22,10 +21,10 @@ func NewCmdGetGlobalFolderStatus(client *cip.APIClient, log *zerolog.Logger) *co return cmd } -func getGlobalFolderStatus(jobId string, client *cip.APIClient, log *zerolog.Logger) { +func getGlobalFolderStatus(jobId string, client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.GetGlobalFolderAsyncStatus(jobId) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to get global folder job status") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/folders/get_personal_folder/get_personal_folder.go b/pkg/cmd/folders/get_personal_folder/get_personal_folder.go index 39e58c61..ef3018d8 100644 --- a/pkg/cmd/folders/get_personal_folder/get_personal_folder.go +++ b/pkg/cmd/folders/get_personal_folder/get_personal_folder.go @@ -1,27 +1,26 @@ package get_personal_folder import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdGetPersonalFolder(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdGetPersonalFolder(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "get-personal-folder", Short: "Get the personal folder of the current user.", Run: func(cmd *cobra.Command, args []string) { - getPersonalFolder(client, log) + getPersonalFolder(client) }, } return cmd } -func getPersonalFolder(client *cip.APIClient, log *zerolog.Logger) { +func getPersonalFolder(client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.GetPersonalFolder() if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to get personal folder") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/folders/update/update.go b/pkg/cmd/folders/update/update.go index ae35240b..6bb633e0 100644 --- a/pkg/cmd/folders/update/update.go +++ b/pkg/cmd/folders/update/update.go @@ -2,14 +2,13 @@ package update import ( "github.com/antihax/optional" - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdUpdate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdUpdate(client *cip.APIClient) *cobra.Command { var ( name string description string @@ -20,7 +19,7 @@ func NewCmdUpdate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { Use: "update", Short: "Update an existing folder with the given identifier.", Run: func(cmd *cobra.Command, args []string) { - update(name, description, id, isAdminMode, client, log) + update(name, description, id, isAdminMode, client) }, } cmd.Flags().StringVar(&name, "name", "", "Specify a name for the folder") @@ -32,16 +31,16 @@ func NewCmdUpdate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { return cmd } -func update(name string, description string, id string, isAdminMode bool, client *cip.APIClient, log *zerolog.Logger) { +func update(name string, description string, id string, isAdminMode bool, client *cip.APIClient) { adminMode := cmdutils.AdminMode(isAdminMode) apiResponse, httpResponse, errorResponse := client.UpdateFolder(types.UpdateFolderRequest{ Name: name, Description: description, - }, id, &types.FolderManagementApiUpdateFolderOpts{ + }, id, &types.FolderOpts{ IsAdminMode: optional.NewString(adminMode), }) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to update folder") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/health-events/list/list.go b/pkg/cmd/health-events/list/list.go deleted file mode 100644 index 9eda2f2d..00000000 --- a/pkg/cmd/health-events/list/list.go +++ /dev/null @@ -1,63 +0,0 @@ -package list - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "net/url" - "strconv" -) - -func NewCmdHealthEventsList() *cobra.Command { - var limit int - - cmd := &cobra.Command{ - Use: "list", - Short: "Get a list of all the unresolved health events in your account.", - Run: func(cmd *cobra.Command, args []string) { - listHealthEvents(limit) - }, - } - cmd.Flags().IntVar(&limit, "limit", 100, "Specify the number of health events to return") - return cmd -} - -func listHealthEvents(limit int) { - var healthEventsResponse api.ListHealthEvent - log := logging.GetConsoleLogger() - requestUrl := "/v1/healthEvents" - client, request := factory.NewHttpRequest("GET", requestUrl) - query := url.Values{} - query.Add("limit", strconv.Itoa(limit)) - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &healthEventsResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - healthEventsResponseJson, err := json.MarshalIndent(healthEventsResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(healthEventsResponseJson)) - } -} diff --git a/pkg/cmd/health-events/get/get.go b/pkg/cmd/health_events/get/get.go similarity index 55% rename from pkg/cmd/health-events/get/get.go rename to pkg/cmd/health_events/get/get.go index 192d4251..60a785cc 100644 --- a/pkg/cmd/health-events/get/get.go +++ b/pkg/cmd/health_events/get/get.go @@ -1,18 +1,16 @@ package get import ( - "encoding/json" "fmt" + "github.com/antihax/optional" "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "net/url" - "strconv" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" + "os" ) -func NewCmdHealthEventsGet() *cobra.Command { +func NewCmdHealthEventsGet(client *cip.APIClient) *cobra.Command { var ( collector bool collectorId string @@ -20,20 +18,19 @@ func NewCmdHealthEventsGet() *cobra.Command { id string ingestBudget bool ingestBudgetFieldValue string - limit int + limit int32 logsToMetricsRule bool name string organisation bool scope string source bool ) - cmd := &cobra.Command{ Use: "get", Short: "Get a list of all the unresolved events in your account that belong to the supplied resource identifiers.", Run: func(cmd *cobra.Command, args []string) { getCollectorEvents(collector, collectorId, collectorName, id, ingestBudget, ingestBudgetFieldValue, limit, - logsToMetricsRule, name, organisation, scope, source) + logsToMetricsRule, name, organisation, scope, source, client) }, } cmd.Flags().BoolVar(&collector, "collector", false, "Set to true if the resource is a collector") @@ -45,7 +42,7 @@ func NewCmdHealthEventsGet() *cobra.Command { cmd.Flags().BoolVar(&ingestBudget, "ingestBudget", false, "Set to true if the resource is a ingest budget") cmd.Flags().StringVar(&ingestBudgetFieldValue, "ingestBudgetFieldValue", "", "Specify the unique field value "+ "of the ingest budget v1. This will be empty for v2 budgets. (this is only used when the ingestBudget argument is set.)") - cmd.Flags().IntVar(&limit, "limit", 100, "Specify the number of health events to return") + cmd.Flags().Int32Var(&limit, "limit", 100, "Specify the number of health events to return") cmd.Flags().BoolVar(&logsToMetricsRule, "logsToMetricsRule", false, "Set to true if the resource is a "+ "logs to metrics rule.") cmd.Flags().StringVar(&name, "name", "Unknown", "Specify the name of the resource if required") @@ -58,11 +55,13 @@ func NewCmdHealthEventsGet() *cobra.Command { } func getCollectorEvents(collector bool, collectorId string, collectorName string, id string, ingestBudget bool, - ingestBudgetFieldValue string, limit int, logsToMetricsRule bool, name string, organisation bool, scope string, source bool) { - var healthEventsResponse api.ListHealthEvent - log := logging.GetConsoleLogger() - requestBodySchema := &api.CreateHealthEventRequest{} - requestBodySchemaData := api.HealthEventRequest{ + ingestBudgetFieldValue string, limit int32, logsToMetricsRule bool, name string, organisation bool, scope string, source bool, + client *cip.APIClient) { + var options types.HealthEventsOpts + var paginationToken string + options.Limit = optional.NewInt32(limit) + body := types.ResourceIdentities{} + bodyData := types.ResourceIdentity{ CollectorId: collectorId, CollectorName: collectorName, Id: id, @@ -71,52 +70,40 @@ func getCollectorEvents(collector bool, collectorId string, collectorName string Scope: scope, } if collector == true { - requestBodySchemaData.Type = "Collector" - } else if ingestBudget == true { - requestBodySchemaData.Type = "IngestBudget" - } else if logsToMetricsRule == true { - requestBodySchemaData.Type = "LogsToMetricsRule" + bodyData.Type_ = "Collector" } else if organisation == true { - requestBodySchemaData.Type = "Organisation" + bodyData.Type_ = "Organisation" + } else if logsToMetricsRule == true { + bodyData.Type_ = "LogsToMetricsRule" + } else if ingestBudget == true { + bodyData.Type_ = "IngestBudget" } else if source == true { - requestBodySchemaData.Type = "Source" + bodyData.Type_ = "Source" } else { - log.Error().Msg("please specify one of the following arguments: collector, ingestBudget, logsToMetricsRule, organisation or source") - } - requestBodySchema.Data = append(requestBodySchema.Data, requestBodySchemaData) - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("failed to marshal request body") - } - requestUrl := "/v1/healthEvents/resources" - client, request := factory.NewHttpRequestWithBody("POST", requestUrl, requestBody) - query := url.Values{} - query.Add("limit", strconv.Itoa(limit)) - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") + fmt.Println("Please specify one of the following arguments: collector, ingestBudget, logsToMetricsRule, organisation or source") + os.Exit(1) } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &healthEventsResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") + body.Data = append(body.Data, bodyData) + apiResponse, httpResponse, errorResponse := client.ListAllHealthEventsForResources(body, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } - - healthEventsResponseJson, err := json.MarshalIndent(healthEventsResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") + paginationToken = apiResponse.Next + for paginationToken != "" { + apiResponse = listAllHealthEventsForResourcesPagination(client, body, options, paginationToken) + paginationToken = apiResponse.Next } +} - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) +func listAllHealthEventsForResourcesPagination(client *cip.APIClient, body types.ResourceIdentities, options types.HealthEventsOpts, token string) types.ListHealthEventResponse { + options.Token = optional.NewString(token) + apiResponse, httpResponse, errorResponse := client.ListAllHealthEventsForResources(body, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) } else { - fmt.Println(string(healthEventsResponseJson)) + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } + return apiResponse } diff --git a/pkg/cmd/health-events/health-events.go b/pkg/cmd/health_events/health_events.go similarity index 63% rename from pkg/cmd/health-events/health-events.go rename to pkg/cmd/health_events/health_events.go index 2b9ba0fe..9a066f44 100644 --- a/pkg/cmd/health-events/health-events.go +++ b/pkg/cmd/health_events/health_events.go @@ -2,18 +2,19 @@ package health_events import ( "github.com/spf13/cobra" - NewCmdHealthEventsGet "github.com/wizedkyle/sumocli/pkg/cmd/health-events/get" - NewCmdHealthEventsList "github.com/wizedkyle/sumocli/pkg/cmd/health-events/list" + NewCmdHealthEventsGet "github.com/wizedkyle/sumocli/pkg/cmd/health_events/get" + NewCmdHealthEventsList "github.com/wizedkyle/sumocli/pkg/cmd/health_events/list" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdHealthEvents() *cobra.Command { +func NewCmdHealthEvents(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "health-events", Short: "Manages health events", Long: "Health Events allow you to keep track of the health of your Collectors and Sources. " + "You can use them to find and investigate common errors and warnings that are known to cause collection issues.", } - cmd.AddCommand(NewCmdHealthEventsGet.NewCmdHealthEventsGet()) - cmd.AddCommand(NewCmdHealthEventsList.NewCmdHealthEventsList()) + cmd.AddCommand(NewCmdHealthEventsGet.NewCmdHealthEventsGet(client)) + cmd.AddCommand(NewCmdHealthEventsList.NewCmdHealthEventsList(client)) return cmd } diff --git a/pkg/cmd/health_events/list/list.go b/pkg/cmd/health_events/list/list.go new file mode 100644 index 00000000..93d8565d --- /dev/null +++ b/pkg/cmd/health_events/list/list.go @@ -0,0 +1,50 @@ +package list + +import ( + "github.com/antihax/optional" + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdHealthEventsList(client *cip.APIClient) *cobra.Command { + var limit int32 + cmd := &cobra.Command{ + Use: "list", + Short: "Get a list of all the unresolved health events in your account.", + Run: func(cmd *cobra.Command, args []string) { + listHealthEvents(limit, client) + }, + } + cmd.Flags().Int32Var(&limit, "limit", 100, "Specify the number of health events to return") + return cmd +} + +func listHealthEvents(limit int32, client *cip.APIClient) { + var options types.HealthEventsOpts + var paginationToken string + options.Limit = optional.NewInt32(limit) + apiResponse, httpResponse, errorResponse := client.ListAllHealthEvents(&options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + paginationToken = apiResponse.Next + for paginationToken != "" { + apiResponse = listHealthEventsPagination(client, options, paginationToken) + paginationToken = apiResponse.Next + } +} + +func listHealthEventsPagination(client *cip.APIClient, options types.HealthEventsOpts, token string) types.ListHealthEventResponse { + options.Token = optional.NewString(token) + apiResponse, httpResponse, errorResponse := client.ListAllHealthEvents(&options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + return apiResponse +} diff --git a/pkg/cmd/ingest-budgets-v2/create/create.go b/pkg/cmd/ingest-budgets-v2/create/create.go deleted file mode 100644 index 824360a0..00000000 --- a/pkg/cmd/ingest-budgets-v2/create/create.go +++ /dev/null @@ -1,96 +0,0 @@ -package create - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdIngestBudgetsV2Create() *cobra.Command { - var ( - action string - auditThreshold int - capacityBytes int - description string - scope string - name string - resetTime string - timezone string - ) - - cmd := &cobra.Command{ - Use: "create", - Short: "Create a new ingest budget.", - Run: func(cmd *cobra.Command, args []string) { - createIngestBudgetV2(action, auditThreshold, capacityBytes, description, name, resetTime, scope, timezone) - }, - } - cmd.Flags().StringVar(&action, "action", "", "Specify an action to take when ingest budget's capacity is reached."+ - "Supported values are either stopCollecting or keepCollecting.") - cmd.Flags().IntVar(&auditThreshold, "auditThreshold", 1, "Specify a percentage of when an ingest budget's capacity usage is logged in the Audit Index") - cmd.Flags().IntVar(&capacityBytes, "capacityBytes", 0, "Specify the capacity of the ingest budget in bytes.") - cmd.Flags().StringVar(&description, "description", "", "Specify a description for the ingest budget") - cmd.Flags().StringVar(&name, "name", "", "Specify a name for the ingest budget") - cmd.Flags().StringVar(&resetTime, "resetTime", "", "Specify the reset time of the ingest bidget in HH:MM format") - cmd.Flags().StringVar(&scope, "scope", "", "Specify a scope which will be used to identify the messages on which the budget needs to be applied") - cmd.Flags().StringVar(&timezone, "timezone", "", "Specify the timezone of the reset time in IANA Time Zone format") - cmd.MarkFlagRequired("action") - cmd.MarkFlagRequired("capacityBytes") - cmd.MarkFlagRequired("name") - cmd.MarkFlagRequired("resetTime") - cmd.MarkFlagRequired("scope") - cmd.MarkFlagRequired("timezone") - return cmd -} - -func createIngestBudgetV2(action string, auditThreshold int, capacityBytes int, description string, name string, - resetTime string, scope string, timezone string) { - var ingestBudgetResponse api.GetIngestBudgetV2 - log := logging.GetConsoleLogger() - requestBodySchema := api.CreateIngestBudgetV2Request{ - Name: name, - Scope: scope, - CapacityBytes: capacityBytes, - Timezone: timezone, - ResetTime: resetTime, - Description: description, - Action: action, - AuditThreshold: auditThreshold, - } - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("failed to marshal request body") - } - requestUrl := "/v2/ingestBudgets" - client, request := factory.NewHttpRequestWithBody("POST", requestUrl, requestBody) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &ingestBudgetResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - ingestBudgetResponseJson, err := json.MarshalIndent(ingestBudgetResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal lookupTableResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(ingestBudgetResponseJson)) - } -} diff --git a/pkg/cmd/ingest-budgets-v2/delete/delete.go b/pkg/cmd/ingest-budgets-v2/delete/delete.go deleted file mode 100644 index e609c290..00000000 --- a/pkg/cmd/ingest-budgets-v2/delete/delete.go +++ /dev/null @@ -1,52 +0,0 @@ -package delete - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdIngestBudgetsV2Delete() *cobra.Command { - var id string - - cmd := &cobra.Command{ - Use: "delete", - Short: "Delete an ingest budget with the given identifier.", - Run: func(cmd *cobra.Command, args []string) { - deleteIngestBudgetV2(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") - cmd.MarkFlagRequired("id") - return cmd -} - -func deleteIngestBudgetV2(id string) { - log := logging.GetConsoleLogger() - requestUrl := "/v2/ingestBudgets/" + id - client, request := factory.NewHttpRequest("DELETE", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - if response.StatusCode != 204 { - var responseError api.ResponseError - err := json.Unmarshal(responseBody, &responseError) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - } else { - fmt.Println("The ingest budget was deleted successfully.") - } -} diff --git a/pkg/cmd/ingest-budgets-v2/get/get.go b/pkg/cmd/ingest-budgets-v2/get/get.go deleted file mode 100644 index 2d7eac41..00000000 --- a/pkg/cmd/ingest-budgets-v2/get/get.go +++ /dev/null @@ -1,59 +0,0 @@ -package get - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdIngestBudgetsV2Get() *cobra.Command { - var id string - - cmd := &cobra.Command{ - Use: "get", - Short: "Get an ingest budget by the given identifier.", - Run: func(cmd *cobra.Command, args []string) { - getIngestBudgetV2(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") - cmd.MarkFlagRequired("id") - return cmd -} - -func getIngestBudgetV2(id string) { - var ingestBudgetResponse api.GetIngestBudgetV2 - log := logging.GetConsoleLogger() - requestUrl := "/v2/ingestBudgets/" + id - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &ingestBudgetResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - ingestBudgetResponseJson, err := json.MarshalIndent(ingestBudgetResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(ingestBudgetResponseJson)) - } -} diff --git a/pkg/cmd/ingest-budgets-v2/list/list.go b/pkg/cmd/ingest-budgets-v2/list/list.go deleted file mode 100644 index 909c02b4..00000000 --- a/pkg/cmd/ingest-budgets-v2/list/list.go +++ /dev/null @@ -1,63 +0,0 @@ -package list - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "net/url" - "strconv" -) - -func NewCmdIngestBudgetsV2List() *cobra.Command { - var limit int - - cmd := &cobra.Command{ - Use: "list", - Short: "Get a list of all ingest budgets.", - Run: func(cmd *cobra.Command, args []string) { - listIngestBudgetsV2(limit) - }, - } - cmd.Flags().IntVar(&limit, "limit", 100, "Specify the number of results to return maximum is 1000") - return cmd -} - -func listIngestBudgetsV2(limit int) { - var ingestBudgetResponse api.ListIngestBudgetsV2 - log := logging.GetConsoleLogger() - requestUrl := "/v2/ingestBudgets" - client, request := factory.NewHttpRequest("GET", requestUrl) - query := url.Values{} - query.Add("limit", strconv.Itoa(limit)) - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &ingestBudgetResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - ingestBudgetResponseJson, err := json.MarshalIndent(ingestBudgetResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(ingestBudgetResponseJson)) - } -} diff --git a/pkg/cmd/ingest-budgets-v2/reset/reset.go b/pkg/cmd/ingest-budgets-v2/reset/reset.go deleted file mode 100644 index fb306d2e..00000000 --- a/pkg/cmd/ingest-budgets-v2/reset/reset.go +++ /dev/null @@ -1,52 +0,0 @@ -package reset - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdIngestBudgetsV2Reset() *cobra.Command { - var id string - - cmd := &cobra.Command{ - Use: "reset", - Short: "Reset ingest budget's current usage to 0 before the scheduled reset time.", - Run: func(cmd *cobra.Command, args []string) { - resetIngestBudgetV2(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") - cmd.MarkFlagRequired("id") - return cmd -} - -func resetIngestBudgetV2(id string) { - log := logging.GetConsoleLogger() - requestUrl := "/v2/ingestBudgets/" + id + "/usage/reset" - client, request := factory.NewHttpRequest("POST", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - if response.StatusCode != 204 { - var responseError api.ResponseError - err := json.Unmarshal(responseBody, &responseError) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - } else { - fmt.Println("Ingest budget's usage was reset successfully.") - } -} diff --git a/pkg/cmd/ingest-budgets-v2/update/update.go b/pkg/cmd/ingest-budgets-v2/update/update.go deleted file mode 100644 index 95430274..00000000 --- a/pkg/cmd/ingest-budgets-v2/update/update.go +++ /dev/null @@ -1,201 +0,0 @@ -package update - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "strconv" - "strings" -) - -func NewCmdIngestBudgetsV2Update() *cobra.Command { - var ( - action string - auditThreshold int - capacityBytes int - description string - id string - merge bool - name string - resetTime string - scope string - timezone string - ) - - cmd := &cobra.Command{ - Use: "update", - Short: "Update an existing ingest budget.", - Run: func(cmd *cobra.Command, args []string) { - updateIngestBudgetV2(action, auditThreshold, capacityBytes, description, id, merge, name, - resetTime, scope, timezone) - }, - } - cmd.Flags().StringVar(&action, "action", "", "Specify an action to take when ingest budget's capacity is reached."+ - "Supported values are either stopCollecting or keepCollecting.") - cmd.Flags().IntVar(&auditThreshold, "auditThreshold", 1, "Specify a percentage of when an ingest budget's capacity usage is logged in the Audit Index") - cmd.Flags().IntVar(&capacityBytes, "capacityBytes", 0, "Specify the capacity of the ingest budget in bytes.") - cmd.Flags().StringVar(&description, "description", "", "Specify a description for the ingest budget") - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") - cmd.Flags().BoolVar(&merge, "merge", true, "If set to false it will overwrite the ingest budget configuration") - cmd.Flags().StringVar(&name, "name", "", "Specify a name for the ingest budget") - cmd.Flags().StringVar(&resetTime, "resetTime", "", "Specify the reset time of the ingest bidget in HH:MM format") - cmd.Flags().StringVar(&scope, "scope", "", "Specify a scope which will be used to identify the messages on which the budget needs to be applied") - cmd.Flags().StringVar(&timezone, "timezone", "", "Specify the timezone of the reset time in IANA Time Zone format") - cmd.MarkFlagRequired("action") - cmd.MarkFlagRequired("capacityBytes") - cmd.MarkFlagRequired("id") - cmd.MarkFlagRequired("name") - cmd.MarkFlagRequired("resetTime") - cmd.MarkFlagRequired("scope") - cmd.MarkFlagRequired("timezone") - return cmd -} - -func updateIngestBudgetV2(action string, auditThreshold int, capacityBytes int, description string, id string, merge bool, - name string, resetTime string, scope string, timezone string) { - var ingestBudgetResponse api.GetIngestBudgetV2 - log := logging.GetConsoleLogger() - if merge == true { - requestUrl := "/v2/ingestBudgets/" + id - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request " + requestUrl) - } - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("error reading response body from request") - } - err = json.Unmarshal(responseBody, &ingestBudgetResponse) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - if response.StatusCode != 200 { - log.Fatal().Msg("Error code = " + strconv.Itoa(response.StatusCode) + string(responseBody)) - } - - // Building body payload to update the ingest budget based on the differences - // between the current ingest budget and the desired settings - requestBodySchema := &api.GetIngestBudgetV2{} - if strings.EqualFold(ingestBudgetResponse.Action, action) { - requestBodySchema.Action = ingestBudgetResponse.Action - } else { - requestBodySchema.Action = action - } - - if ingestBudgetResponse.AuditThreshold == auditThreshold { - requestBodySchema.AuditThreshold = ingestBudgetResponse.AuditThreshold - } else { - requestBodySchema.AuditThreshold = auditThreshold - } - - if ingestBudgetResponse.CapacityBytes == capacityBytes { - requestBodySchema.CapacityBytes = ingestBudgetResponse.CapacityBytes - } else { - requestBodySchema.CapacityBytes = capacityBytes - } - - if strings.EqualFold(ingestBudgetResponse.Description, description) { - requestBodySchema.Description = ingestBudgetResponse.Description - } else { - requestBodySchema.Description = description - } - - if strings.EqualFold(ingestBudgetResponse.Name, name) { - requestBodySchema.Name = ingestBudgetResponse.Name - } else { - requestBodySchema.Name = name - } - - if strings.EqualFold(ingestBudgetResponse.ResetTime, resetTime) { - requestBodySchema.ResetTime = ingestBudgetResponse.ResetTime - } else { - requestBodySchema.ResetTime = resetTime - } - - if strings.EqualFold(ingestBudgetResponse.Scope, scope) { - requestBodySchema.Scope = ingestBudgetResponse.Scope - } else { - requestBodySchema.Scope = scope - } - - if strings.EqualFold(ingestBudgetResponse.Timezone, timezone) { - requestBodySchema.Timezone = ingestBudgetResponse.Timezone - } else { - requestBodySchema.Timezone = timezone - } - - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("failed to marshal request body") - } - client, request = factory.NewHttpRequestWithBody("PUT", requestUrl, requestBody) - response, err = client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request " + requestUrl) - } - defer response.Body.Close() - responseBody, err = io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("error reading response body from request") - } - err = json.Unmarshal(responseBody, &ingestBudgetResponse) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - ingestBudgetResponseJson, err := json.MarshalIndent(ingestBudgetResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("error marshalling response body") - } - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(ingestBudgetResponseJson)) - } - } else { - requestBodySchema := api.CreateIngestBudgetV2Request{ - Name: name, - Scope: scope, - CapacityBytes: capacityBytes, - Timezone: timezone, - ResetTime: resetTime, - Description: description, - Action: action, - AuditThreshold: auditThreshold, - } - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("failed to marshal request body") - } - requestUrl := "/v2/ingestBudgets/" + id - client, request := factory.NewHttpRequestWithBody("PUT", requestUrl, requestBody) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("error reading response body from request") - } - err = json.Unmarshal(responseBody, &ingestBudgetResponse) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - ingestBudgetResponseJson, err := json.MarshalIndent(ingestBudgetResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("error marshalling response body") - } - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(ingestBudgetResponseJson)) - } - } -} diff --git a/pkg/cmd/ingest-budgets/assign-collector/assign-collector.go b/pkg/cmd/ingest-budgets/assign-collector/assign-collector.go deleted file mode 100644 index de28f3c6..00000000 --- a/pkg/cmd/ingest-budgets/assign-collector/assign-collector.go +++ /dev/null @@ -1,64 +0,0 @@ -package assign_collector - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdIngestBudgetsAssignCollector() *cobra.Command { - var ( - collectorId string - id string - ) - - cmd := &cobra.Command{ - Use: "assign-collector", - Short: "Assign a Collector to a budget.", - Run: func(cmd *cobra.Command, args []string) { - assignCollector(collectorId, id) - }, - } - cmd.Flags().StringVar(&collectorId, "collectorId", "", "Specify the collector id to add to the ingest budget") - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") - cmd.MarkFlagRequired("collectorId") - cmd.MarkFlagRequired("id") - return cmd -} - -func assignCollector(collectorId string, id string) { - var ingestBudgetResponse api.GetIngestBudget - log := logging.GetConsoleLogger() - requestUrl := "/v1/ingestBudgets/" + id + "/collectors/" + collectorId - client, request := factory.NewHttpRequest("PUT", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &ingestBudgetResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - ingestBudgetResponseJson, err := json.MarshalIndent(ingestBudgetResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(ingestBudgetResponseJson)) - } -} diff --git a/pkg/cmd/ingest-budgets/create/create.go b/pkg/cmd/ingest-budgets/create/create.go deleted file mode 100644 index 0c1b189f..00000000 --- a/pkg/cmd/ingest-budgets/create/create.go +++ /dev/null @@ -1,96 +0,0 @@ -package create - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdIngestBudgetsCreate() *cobra.Command { - var ( - action string - auditThreshold int - capacityBytes int - description string - fieldValue string - name string - resetTime string - timezone string - ) - - cmd := &cobra.Command{ - Use: "create", - Short: "Create a new ingest budget.", - Run: func(cmd *cobra.Command, args []string) { - createIngestBudget(action, auditThreshold, capacityBytes, description, fieldValue, name, resetTime, timezone) - }, - } - cmd.Flags().StringVar(&action, "action", "", "Specify an action to take when ingest budget's capacity is reached."+ - "Supported values are either stopCollecting or keepCollecting.") - cmd.Flags().IntVar(&auditThreshold, "auditThreshold", 1, "Specify a percentage of when an ingest budget's capacity usage is logged in the Audit Index") - cmd.Flags().IntVar(&capacityBytes, "capacityBytes", 0, "Specify the capacity of the ingest budget in bytes.") - cmd.Flags().StringVar(&description, "description", "", "Specify a description for the ingest budget") - cmd.Flags().StringVar(&fieldValue, "fieldValue", "", "Specify the custom field value that is used to assign Collectors to the ingest budget") - cmd.Flags().StringVar(&name, "name", "", "Specify a name for the ingest budget") - cmd.Flags().StringVar(&resetTime, "resetTime", "", "Specify the reset time of the ingest bidget in HH:MM format") - cmd.Flags().StringVar(&timezone, "timezone", "", "Specify the timezone of the reset time in IANA Time Zone format") - cmd.MarkFlagRequired("action") - cmd.MarkFlagRequired("capacityBytes") - cmd.MarkFlagRequired("fieldValue") - cmd.MarkFlagRequired("name") - cmd.MarkFlagRequired("resetTime") - cmd.MarkFlagRequired("timezone") - return cmd -} - -func createIngestBudget(action string, auditThreshold int, capacityBytes int, description string, - fieldValue string, name string, resetTime string, timezone string) { - var ingestBudgetResponse api.GetIngestBudget - log := logging.GetConsoleLogger() - requestBodySchema := api.CreateIngestBudgetRequest{ - Name: name, - FieldValue: fieldValue, - CapacityBytes: capacityBytes, - Timezone: timezone, - ResetTime: resetTime, - Description: description, - Action: action, - AuditThreshold: auditThreshold, - } - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("failed to marshal request body") - } - requestUrl := "/v1/ingestBudgets" - client, request := factory.NewHttpRequestWithBody("POST", requestUrl, requestBody) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &ingestBudgetResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - ingestBudgetResponseJson, err := json.MarshalIndent(ingestBudgetResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal lookupTableResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(ingestBudgetResponseJson)) - } -} diff --git a/pkg/cmd/ingest-budgets/delete/delete.go b/pkg/cmd/ingest-budgets/delete/delete.go deleted file mode 100644 index be5d8781..00000000 --- a/pkg/cmd/ingest-budgets/delete/delete.go +++ /dev/null @@ -1,52 +0,0 @@ -package delete - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdIngestBudgetsDelete() *cobra.Command { - var id string - - cmd := &cobra.Command{ - Use: "delete", - Short: "Delete an ingest budget with the given identifier.", - Run: func(cmd *cobra.Command, args []string) { - deleteIngestBudget(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") - cmd.MarkFlagRequired("id") - return cmd -} - -func deleteIngestBudget(id string) { - log := logging.GetConsoleLogger() - requestUrl := "/v1/ingestBudgets/" + id - client, request := factory.NewHttpRequest("DELETE", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - if response.StatusCode != 204 { - var responseError api.ResponseError - err := json.Unmarshal(responseBody, &responseError) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - } else { - fmt.Println("The ingest budget was deleted successfully.") - } -} diff --git a/pkg/cmd/ingest-budgets/get-associated-collectors/get-associated-collectors.go b/pkg/cmd/ingest-budgets/get-associated-collectors/get-associated-collectors.go deleted file mode 100644 index e155a25c..00000000 --- a/pkg/cmd/ingest-budgets/get-associated-collectors/get-associated-collectors.go +++ /dev/null @@ -1,68 +0,0 @@ -package get_associated_collectors - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "net/url" - "strconv" -) - -func NewCmdIngestBudgetsGetAssociatedCollectors() *cobra.Command { - var ( - id string - limit int - ) - - cmd := &cobra.Command{ - Use: "get-associated-collectors", - Short: "Get a list of Collectors assigned to an ingest budget.", - Run: func(cmd *cobra.Command, args []string) { - getAssociatedCollectors(id, limit) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") - cmd.Flags().IntVar(&limit, "limit", 100, "Specify the number of results to return maximum is 1000") - cmd.MarkFlagRequired("id") - return cmd -} - -func getAssociatedCollectors(id string, limit int) { - var associatedCollectorsResponse api.GetAssociatedCollectors - log := logging.GetConsoleLogger() - requestUrl := "/v1/ingestBudgets/" + id + "/collectors" - client, request := factory.NewHttpRequest("GET", requestUrl) - query := url.Values{} - query.Add("limit", strconv.Itoa(limit)) - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &associatedCollectorsResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - associatedCollectorResponseJson, err := json.MarshalIndent(associatedCollectorsResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(associatedCollectorResponseJson)) - } -} diff --git a/pkg/cmd/ingest-budgets/get/get.go b/pkg/cmd/ingest-budgets/get/get.go deleted file mode 100644 index 685132be..00000000 --- a/pkg/cmd/ingest-budgets/get/get.go +++ /dev/null @@ -1,59 +0,0 @@ -package get - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdIngestBudgetsGet() *cobra.Command { - var id string - - cmd := &cobra.Command{ - Use: "get", - Short: "Get an ingest budget by the given identifier.", - Run: func(cmd *cobra.Command, args []string) { - getIngestBudget(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") - cmd.MarkFlagRequired("id") - return cmd -} - -func getIngestBudget(id string) { - var ingestBudgetResponse api.GetIngestBudget - log := logging.GetConsoleLogger() - requestUrl := "/v1/ingestBudgets/" + id - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &ingestBudgetResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - ingestBudgetResponseJson, err := json.MarshalIndent(ingestBudgetResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(ingestBudgetResponseJson)) - } -} diff --git a/pkg/cmd/ingest-budgets/list/list.go b/pkg/cmd/ingest-budgets/list/list.go deleted file mode 100644 index 32ef9357..00000000 --- a/pkg/cmd/ingest-budgets/list/list.go +++ /dev/null @@ -1,63 +0,0 @@ -package list - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "net/url" - "strconv" -) - -func NewCmdIngestBudgetsList() *cobra.Command { - var limit int - - cmd := &cobra.Command{ - Use: "list", - Short: "Get a list of all ingest budgets.", - Run: func(cmd *cobra.Command, args []string) { - listIngestBudgets(limit) - }, - } - cmd.Flags().IntVar(&limit, "limit", 100, "Specify the number of results to return maximum is 1000") - return cmd -} - -func listIngestBudgets(limit int) { - var ingestBudgetResponse api.ListIngestBudgets - log := logging.GetConsoleLogger() - requestUrl := "/v1/ingestBudgets" - client, request := factory.NewHttpRequest("GET", requestUrl) - query := url.Values{} - query.Add("limit", strconv.Itoa(limit)) - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &ingestBudgetResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - ingestBudgetResponseJson, err := json.MarshalIndent(ingestBudgetResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(ingestBudgetResponseJson)) - } -} diff --git a/pkg/cmd/ingest-budgets/remove-collector/remove-collector.go b/pkg/cmd/ingest-budgets/remove-collector/remove-collector.go deleted file mode 100644 index 44b526fd..00000000 --- a/pkg/cmd/ingest-budgets/remove-collector/remove-collector.go +++ /dev/null @@ -1,64 +0,0 @@ -package remove_collector - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmIngestBudgetsRemoveAssociatedCollector() *cobra.Command { - var ( - collectorId string - id string - ) - - cmd := &cobra.Command{ - Use: "remove-collector", - Short: "Remove Collector from a budget.", - Run: func(cmd *cobra.Command, args []string) { - removeAssociatedCollector(collectorId, id) - }, - } - cmd.Flags().StringVar(&collectorId, "collectorId", "", "Specify the collector id to remove from the ingest budget") - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") - cmd.MarkFlagRequired("collectorId") - cmd.MarkFlagRequired("id") - return cmd -} - -func removeAssociatedCollector(collectorId string, id string) { - var ingestBudgetResponse api.GetIngestBudget - log := logging.GetConsoleLogger() - requestUrl := "/v1/ingestBudgets/" + id + "/collectors/" + collectorId - client, request := factory.NewHttpRequest("DELETE", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &ingestBudgetResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - ingestBudgetResponseJson, err := json.MarshalIndent(ingestBudgetResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(ingestBudgetResponseJson)) - } -} diff --git a/pkg/cmd/ingest-budgets/reset/reset.go b/pkg/cmd/ingest-budgets/reset/reset.go deleted file mode 100644 index ae957d65..00000000 --- a/pkg/cmd/ingest-budgets/reset/reset.go +++ /dev/null @@ -1,52 +0,0 @@ -package reset - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdIngestBudgetsReset() *cobra.Command { - var id string - - cmd := &cobra.Command{ - Use: "reset", - Short: "Reset ingest budget's current usage to 0 before the scheduled reset time.", - Run: func(cmd *cobra.Command, args []string) { - resetIngestBudget(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") - cmd.MarkFlagRequired("id") - return cmd -} - -func resetIngestBudget(id string) { - log := logging.GetConsoleLogger() - requestUrl := "/v1/ingestBudgets/" + id + "/usage/reset" - client, request := factory.NewHttpRequest("POST", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - if response.StatusCode != 204 { - var responseError api.ResponseError - err := json.Unmarshal(responseBody, &responseError) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - } else { - fmt.Println("Ingest budget's usage was reset successfully.") - } -} diff --git a/pkg/cmd/ingest-budgets/update/update.go b/pkg/cmd/ingest-budgets/update/update.go deleted file mode 100644 index a83bb8a8..00000000 --- a/pkg/cmd/ingest-budgets/update/update.go +++ /dev/null @@ -1,201 +0,0 @@ -package update - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "strconv" - "strings" -) - -func NewCmdIngestBudgetsUpdate() *cobra.Command { - var ( - action string - auditThreshold int - capacityBytes int - description string - fieldValue string - id string - merge bool - name string - resetTime string - timezone string - ) - - cmd := &cobra.Command{ - Use: "update", - Short: "Update an existing ingest budget.", - Run: func(cmd *cobra.Command, args []string) { - updateIngestBudget(action, auditThreshold, capacityBytes, description, fieldValue, id, merge, - name, resetTime, timezone) - }, - } - cmd.Flags().StringVar(&action, "action", "", "Specify an action to take when ingest budget's capacity is reached."+ - "Supported values are either stopCollecting or keepCollecting.") - cmd.Flags().IntVar(&auditThreshold, "auditThreshold", 1, "Specify a percentage of when an ingest budget's capacity usage is logged in the Audit Index") - cmd.Flags().IntVar(&capacityBytes, "capacityBytes", 0, "Specify the capacity of the ingest budget in bytes.") - cmd.Flags().StringVar(&description, "description", "", "Specify a description for the ingest budget") - cmd.Flags().StringVar(&fieldValue, "fieldValue", "", "Specify the custom field value that is used to assign Collectors to the ingest budget") - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") - cmd.Flags().BoolVar(&merge, "merge", true, "If set to false it will overwrite the ingest budget configuration") - cmd.Flags().StringVar(&name, "name", "", "Specify a name for the ingest budget") - cmd.Flags().StringVar(&resetTime, "resetTime", "", "Specify the reset time of the ingest bidget in HH:MM format") - cmd.Flags().StringVar(&timezone, "timezone", "", "Specify the timezone of the reset time in IANA Time Zone format") - cmd.MarkFlagRequired("action") - cmd.MarkFlagRequired("capacityBytes") - cmd.MarkFlagRequired("fieldValue") - cmd.MarkFlagRequired("id") - cmd.MarkFlagRequired("name") - cmd.MarkFlagRequired("resetTime") - cmd.MarkFlagRequired("timezone") - return cmd -} - -func updateIngestBudget(action string, auditThreshold int, capacityBytes int, description string, fieldValue string, id string, merge bool, - name string, resetTime string, timezone string) { - var ingestBudgetResponse api.GetIngestBudget - log := logging.GetConsoleLogger() - if merge == true { - requestUrl := "/v1/ingestBudgets/" + id - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request " + requestUrl) - } - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("error reading response body from request") - } - err = json.Unmarshal(responseBody, &ingestBudgetResponse) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - if response.StatusCode != 200 { - log.Fatal().Msg("Error code = " + strconv.Itoa(response.StatusCode) + string(responseBody)) - } - - // Building body payload to update the ingest budget based on the differences - // between the current ingest budget and the desired settings - requestBodySchema := &api.CreateIngestBudgetRequest{} - if strings.EqualFold(ingestBudgetResponse.Action, action) { - requestBodySchema.Action = ingestBudgetResponse.Action - } else { - requestBodySchema.Action = action - } - - if ingestBudgetResponse.AuditThreshold == auditThreshold { - requestBodySchema.AuditThreshold = ingestBudgetResponse.AuditThreshold - } else { - requestBodySchema.AuditThreshold = auditThreshold - } - - if ingestBudgetResponse.CapacityBytes == capacityBytes { - requestBodySchema.CapacityBytes = ingestBudgetResponse.CapacityBytes - } else { - requestBodySchema.CapacityBytes = capacityBytes - } - - if strings.EqualFold(ingestBudgetResponse.Description, description) { - requestBodySchema.Description = ingestBudgetResponse.Description - } else { - requestBodySchema.Description = description - } - - if strings.EqualFold(ingestBudgetResponse.FieldValue, fieldValue) { - requestBodySchema.FieldValue = ingestBudgetResponse.FieldValue - } else { - requestBodySchema.FieldValue = fieldValue - } - - if strings.EqualFold(ingestBudgetResponse.Name, name) { - requestBodySchema.Name = ingestBudgetResponse.Name - } else { - requestBodySchema.Name = name - } - - if strings.EqualFold(ingestBudgetResponse.ResetTime, resetTime) { - requestBodySchema.ResetTime = ingestBudgetResponse.ResetTime - } else { - requestBodySchema.ResetTime = resetTime - } - - if strings.EqualFold(ingestBudgetResponse.TimeZone, timezone) { - requestBodySchema.Timezone = ingestBudgetResponse.TimeZone - } else { - requestBodySchema.Timezone = timezone - } - - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("failed to marshal request body") - } - client, request = factory.NewHttpRequestWithBody("PUT", requestUrl, requestBody) - response, err = client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request " + requestUrl) - } - defer response.Body.Close() - responseBody, err = io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("error reading response body from request") - } - err = json.Unmarshal(responseBody, &ingestBudgetResponse) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - ingestBudgetResponseJson, err := json.MarshalIndent(ingestBudgetResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("error marshalling response body") - } - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(ingestBudgetResponseJson)) - } - } else { - requestBodySchema := &api.CreateIngestBudgetRequest{ - Name: name, - FieldValue: fieldValue, - CapacityBytes: capacityBytes, - Timezone: timezone, - ResetTime: resetTime, - Description: description, - Action: action, - AuditThreshold: auditThreshold, - } - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("failed to marshal request body") - } - requestUrl := "/v1/ingestBudgets/" + id - client, request := factory.NewHttpRequestWithBody("PUT", requestUrl, requestBody) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("error reading response body from request") - } - err = json.Unmarshal(responseBody, &ingestBudgetResponse) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - ingestBudgetResponseJson, err := json.MarshalIndent(ingestBudgetResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("error marshalling response body") - } - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(ingestBudgetResponseJson)) - } - } -} diff --git a/pkg/cmd/ingest_budgets/assign_collector/assign_collector.go b/pkg/cmd/ingest_budgets/assign_collector/assign_collector.go new file mode 100644 index 00000000..d009c7a9 --- /dev/null +++ b/pkg/cmd/ingest_budgets/assign_collector/assign_collector.go @@ -0,0 +1,35 @@ +package assign_collector + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdIngestBudgetsAssignCollector(client *cip.APIClient) *cobra.Command { + var ( + collectorId string + id string + ) + cmd := &cobra.Command{ + Use: "assign-collector", + Short: "Assign a Collector to a budget.", + Run: func(cmd *cobra.Command, args []string) { + assignCollector(collectorId, id, client) + }, + } + cmd.Flags().StringVar(&collectorId, "collectorId", "", "Specify the collector id to add to the ingest budget") + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") + cmd.MarkFlagRequired("collectorId") + cmd.MarkFlagRequired("id") + return cmd +} + +func assignCollector(collectorId string, id string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.AssignCollectorToBudget(id, collectorId) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/ingest_budgets/create/create.go b/pkg/cmd/ingest_budgets/create/create.go new file mode 100644 index 00000000..33535814 --- /dev/null +++ b/pkg/cmd/ingest_budgets/create/create.go @@ -0,0 +1,64 @@ +package create + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdIngestBudgetsCreate(client *cip.APIClient) *cobra.Command { + var ( + action string + auditThreshold int32 + capacityBytes int64 + description string + fieldValue string + name string + resetTime string + timezone string + ) + cmd := &cobra.Command{ + Use: "create", + Short: "Create a new ingest budget.", + Run: func(cmd *cobra.Command, args []string) { + createIngestBudget(action, auditThreshold, capacityBytes, description, fieldValue, name, resetTime, timezone, + client) + }, + } + cmd.Flags().StringVar(&action, "action", "", "Specify an action to take when ingest budget's capacity is reached."+ + "Supported values are either stopCollecting or keepCollecting.") + cmd.Flags().Int32Var(&auditThreshold, "auditThreshold", 1, "Specify a percentage of when an ingest budget's capacity usage is logged in the Audit Index") + cmd.Flags().Int64Var(&capacityBytes, "capacityBytes", 0, "Specify the capacity of the ingest budget in bytes.") + cmd.Flags().StringVar(&description, "description", "", "Specify a description for the ingest budget") + cmd.Flags().StringVar(&fieldValue, "fieldValue", "", "Specify the custom field value that is used to assign Collectors to the ingest budget") + cmd.Flags().StringVar(&name, "name", "", "Specify a name for the ingest budget") + cmd.Flags().StringVar(&resetTime, "resetTime", "", "Specify the reset time of the ingest bidget in HH:MM format") + cmd.Flags().StringVar(&timezone, "timezone", "", "Specify the timezone of the reset time in IANA Time Zone format") + cmd.MarkFlagRequired("action") + cmd.MarkFlagRequired("capacityBytes") + cmd.MarkFlagRequired("fieldValue") + cmd.MarkFlagRequired("name") + cmd.MarkFlagRequired("resetTime") + cmd.MarkFlagRequired("timezone") + return cmd +} + +func createIngestBudget(action string, auditThreshold int32, capacityBytes int64, description string, + fieldValue string, name string, resetTime string, timezone string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.CreateIngestBudget(types.IngestBudgetDefinition{ + Name: name, + FieldValue: fieldValue, + CapacityBytes: capacityBytes, + Timezone: timezone, + ResetTime: resetTime, + Description: description, + Action: action, + AuditThreshold: auditThreshold, + }) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/ingest_budgets/delete/delete.go b/pkg/cmd/ingest_budgets/delete/delete.go new file mode 100644 index 00000000..2e337afc --- /dev/null +++ b/pkg/cmd/ingest_budgets/delete/delete.go @@ -0,0 +1,30 @@ +package delete + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdIngestBudgetsDelete(client *cip.APIClient) *cobra.Command { + var id string + cmd := &cobra.Command{ + Use: "delete", + Short: "Delete an ingest budget with the given identifier.", + Run: func(cmd *cobra.Command, args []string) { + deleteIngestBudget(id, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") + cmd.MarkFlagRequired("id") + return cmd +} + +func deleteIngestBudget(id string, client *cip.APIClient) { + httpResponse, errorResponse := client.DeleteIngestBudget(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(nil, httpResponse, errorResponse, "The ingest budget was deleted successfully.") + } +} diff --git a/pkg/cmd/ingest_budgets/get/get.go b/pkg/cmd/ingest_budgets/get/get.go new file mode 100644 index 00000000..687ef3d3 --- /dev/null +++ b/pkg/cmd/ingest_budgets/get/get.go @@ -0,0 +1,31 @@ +package get + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdIngestBudgetsGet(client *cip.APIClient) *cobra.Command { + var id string + + cmd := &cobra.Command{ + Use: "get", + Short: "Get an ingest budget by the given identifier.", + Run: func(cmd *cobra.Command, args []string) { + getIngestBudget(id, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") + cmd.MarkFlagRequired("id") + return cmd +} + +func getIngestBudget(id string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.GetIngestBudget(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/ingest_budgets/get_associated_collectors/get_associated_collectors.go b/pkg/cmd/ingest_budgets/get_associated_collectors/get_associated_collectors.go new file mode 100644 index 00000000..06cf3908 --- /dev/null +++ b/pkg/cmd/ingest_budgets/get_associated_collectors/get_associated_collectors.go @@ -0,0 +1,55 @@ +package get_associated_collectors + +import ( + "github.com/antihax/optional" + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdIngestBudgetsGetAssociatedCollectors(client *cip.APIClient) *cobra.Command { + var ( + id string + limit int32 + ) + cmd := &cobra.Command{ + Use: "get-associated-collectors", + Short: "Get a list of Collectors assigned to an ingest budget.", + Run: func(cmd *cobra.Command, args []string) { + getAssociatedCollectors(id, limit, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") + cmd.Flags().Int32Var(&limit, "limit", 100, "Specify the number of results to return maximum is 1000") + cmd.MarkFlagRequired("id") + return cmd +} + +func getAssociatedCollectors(id string, limit int32, client *cip.APIClient) { + var options types.ListIngestBudgetV1Opts + var paginationToken string + options.Limit = optional.NewInt32(limit) + apiResponse, httpResponse, errorResponse := client.GetAssignedCollectors(id, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + paginationToken = apiResponse.Next + for paginationToken != "" { + apiResponse = getAssociatedCollectorsPagination(client, id, options, paginationToken) + paginationToken = apiResponse.Next + } +} + +func getAssociatedCollectorsPagination(client *cip.APIClient, id string, options types.ListIngestBudgetV1Opts, token string) types.ListCollectorIdentitiesResponse { + options.Token = optional.NewString(token) + apiResponse, httpResponse, errorResponse := client.GetAssignedCollectors(id, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + return apiResponse +} diff --git a/pkg/cmd/ingest-budgets/ingest-budgets.go b/pkg/cmd/ingest_budgets/ingest_budgets.go similarity index 69% rename from pkg/cmd/ingest-budgets/ingest-budgets.go rename to pkg/cmd/ingest_budgets/ingest_budgets.go index 81e9bbd1..22a43307 100644 --- a/pkg/cmd/ingest-budgets/ingest-budgets.go +++ b/pkg/cmd/ingest_budgets/ingest_budgets.go @@ -2,32 +2,33 @@ package ingest_budgets import ( "github.com/spf13/cobra" - NewCmdIngestBudgetsAssignCollector "github.com/wizedkyle/sumocli/pkg/cmd/ingest-budgets/assign-collector" - NewCmdIngestBudgetsCreate "github.com/wizedkyle/sumocli/pkg/cmd/ingest-budgets/create" - NewCmdIngestBudgetsDelete "github.com/wizedkyle/sumocli/pkg/cmd/ingest-budgets/delete" - NewCmdIngestBudgetsGet "github.com/wizedkyle/sumocli/pkg/cmd/ingest-budgets/get" - NewCmdIngestBudgetsGetAssociatedCollectors "github.com/wizedkyle/sumocli/pkg/cmd/ingest-budgets/get-associated-collectors" - NewCmdIngestBudgetsList "github.com/wizedkyle/sumocli/pkg/cmd/ingest-budgets/list" - NewCmdIngestBudgetsRemoveCollector "github.com/wizedkyle/sumocli/pkg/cmd/ingest-budgets/remove-collector" - NewCmdIngestBudgetsReset "github.com/wizedkyle/sumocli/pkg/cmd/ingest-budgets/reset" - NewCmdIngestBudgetsUpdate "github.com/wizedkyle/sumocli/pkg/cmd/ingest-budgets/update" + NewCmdIngestBudgetsAssignCollector "github.com/wizedkyle/sumocli/pkg/cmd/ingest_budgets/assign_collector" + NewCmdIngestBudgetsCreate "github.com/wizedkyle/sumocli/pkg/cmd/ingest_budgets/create" + NewCmdIngestBudgetsDelete "github.com/wizedkyle/sumocli/pkg/cmd/ingest_budgets/delete" + NewCmdIngestBudgetsGet "github.com/wizedkyle/sumocli/pkg/cmd/ingest_budgets/get" + NewCmdIngestBudgetsGetAssociatedCollectors "github.com/wizedkyle/sumocli/pkg/cmd/ingest_budgets/get_associated_collectors" + NewCmdIngestBudgetsList "github.com/wizedkyle/sumocli/pkg/cmd/ingest_budgets/list" + NewCmdIngestBudgetsRemoveCollector "github.com/wizedkyle/sumocli/pkg/cmd/ingest_budgets/remove_collector" + NewCmdIngestBudgetsReset "github.com/wizedkyle/sumocli/pkg/cmd/ingest_budgets/reset" + NewCmdIngestBudgetsUpdate "github.com/wizedkyle/sumocli/pkg/cmd/ingest_budgets/update" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdIngestBudgets() *cobra.Command { +func NewCmdIngestBudgets(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "ingest-budgets", Short: "Manage ingest budgets (v1)", Long: "Commands that allow you to manage ingest budgets (v1)." + "Ingest Budgets allow you to control the capacity of daily ingestion volume sent to Sumo Logic from Collectors.", } - cmd.AddCommand(NewCmdIngestBudgetsAssignCollector.NewCmdIngestBudgetsAssignCollector()) - cmd.AddCommand(NewCmdIngestBudgetsCreate.NewCmdIngestBudgetsCreate()) - cmd.AddCommand(NewCmdIngestBudgetsDelete.NewCmdIngestBudgetsDelete()) - cmd.AddCommand(NewCmdIngestBudgetsGet.NewCmdIngestBudgetsGet()) - cmd.AddCommand(NewCmdIngestBudgetsGetAssociatedCollectors.NewCmdIngestBudgetsGetAssociatedCollectors()) - cmd.AddCommand(NewCmdIngestBudgetsList.NewCmdIngestBudgetsList()) - cmd.AddCommand(NewCmdIngestBudgetsRemoveCollector.NewCmIngestBudgetsRemoveAssociatedCollector()) - cmd.AddCommand(NewCmdIngestBudgetsReset.NewCmdIngestBudgetsReset()) - cmd.AddCommand(NewCmdIngestBudgetsUpdate.NewCmdIngestBudgetsUpdate()) + cmd.AddCommand(NewCmdIngestBudgetsAssignCollector.NewCmdIngestBudgetsAssignCollector(client)) + cmd.AddCommand(NewCmdIngestBudgetsCreate.NewCmdIngestBudgetsCreate(client)) + cmd.AddCommand(NewCmdIngestBudgetsDelete.NewCmdIngestBudgetsDelete(client)) + cmd.AddCommand(NewCmdIngestBudgetsGet.NewCmdIngestBudgetsGet(client)) + cmd.AddCommand(NewCmdIngestBudgetsGetAssociatedCollectors.NewCmdIngestBudgetsGetAssociatedCollectors(client)) + cmd.AddCommand(NewCmdIngestBudgetsList.NewCmdIngestBudgetsList(client)) + cmd.AddCommand(NewCmdIngestBudgetsRemoveCollector.NewCmIngestBudgetsRemoveAssociatedCollector(client)) + cmd.AddCommand(NewCmdIngestBudgetsReset.NewCmdIngestBudgetsReset(client)) + cmd.AddCommand(NewCmdIngestBudgetsUpdate.NewCmdIngestBudgetsUpdate(client)) return cmd } diff --git a/pkg/cmd/ingest_budgets/list/list.go b/pkg/cmd/ingest_budgets/list/list.go new file mode 100644 index 00000000..599090ba --- /dev/null +++ b/pkg/cmd/ingest_budgets/list/list.go @@ -0,0 +1,50 @@ +package list + +import ( + "github.com/antihax/optional" + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdIngestBudgetsList(client *cip.APIClient) *cobra.Command { + var limit int32 + cmd := &cobra.Command{ + Use: "list", + Short: "Get a list of all ingest budgets.", + Run: func(cmd *cobra.Command, args []string) { + listIngestBudgets(limit, client) + }, + } + cmd.Flags().Int32Var(&limit, "limit", 100, "Specify the number of results to return maximum is 1000") + return cmd +} + +func listIngestBudgets(limit int32, client *cip.APIClient) { + var options types.ListIngestBudgetV1Opts + var paginationToken string + options.Limit = optional.NewInt32(limit) + apiResponse, httpResponse, errorResponse := client.ListIngestBudgets(&options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + paginationToken = apiResponse.Next + for paginationToken != "" { + apiResponse = listIngestBudgetsPagination(client, options, paginationToken) + paginationToken = apiResponse.Next + } +} + +func listIngestBudgetsPagination(client *cip.APIClient, options types.ListIngestBudgetV1Opts, token string) types.ListIngestBudgetsResponse { + options.Token = optional.NewString(token) + apiResponse, httpResponse, errorResponse := client.ListIngestBudgets(&options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + return apiResponse +} diff --git a/pkg/cmd/ingest_budgets/remove_collector/remove_collector.go b/pkg/cmd/ingest_budgets/remove_collector/remove_collector.go new file mode 100644 index 00000000..0815d2cf --- /dev/null +++ b/pkg/cmd/ingest_budgets/remove_collector/remove_collector.go @@ -0,0 +1,35 @@ +package remove_collector + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmIngestBudgetsRemoveAssociatedCollector(client *cip.APIClient) *cobra.Command { + var ( + collectorId string + id string + ) + cmd := &cobra.Command{ + Use: "remove-collector", + Short: "Remove Collector from a budget.", + Run: func(cmd *cobra.Command, args []string) { + removeAssociatedCollector(collectorId, id, client) + }, + } + cmd.Flags().StringVar(&collectorId, "collectorId", "", "Specify the collector id to remove from the ingest budget") + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") + cmd.MarkFlagRequired("collectorId") + cmd.MarkFlagRequired("id") + return cmd +} + +func removeAssociatedCollector(collectorId string, id string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.RemoveCollectorFromBudget(id, collectorId) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/ingest_budgets/reset/reset.go b/pkg/cmd/ingest_budgets/reset/reset.go new file mode 100644 index 00000000..952c0636 --- /dev/null +++ b/pkg/cmd/ingest_budgets/reset/reset.go @@ -0,0 +1,30 @@ +package reset + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdIngestBudgetsReset(client *cip.APIClient) *cobra.Command { + var id string + cmd := &cobra.Command{ + Use: "reset", + Short: "Reset ingest budget's current usage to 0 before the scheduled reset time.", + Run: func(cmd *cobra.Command, args []string) { + resetIngestBudget(id, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") + cmd.MarkFlagRequired("id") + return cmd +} + +func resetIngestBudget(id string, client *cip.APIClient) { + httpResponse, errorResponse := client.ResetUsage(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(nil, httpResponse, errorResponse, "Ingest budget's usage was reset successfully.") + } +} diff --git a/pkg/cmd/ingest_budgets/update/update.go b/pkg/cmd/ingest_budgets/update/update.go new file mode 100644 index 00000000..2e428572 --- /dev/null +++ b/pkg/cmd/ingest_budgets/update/update.go @@ -0,0 +1,70 @@ +package update + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdIngestBudgetsUpdate(client *cip.APIClient) *cobra.Command { + var ( + action string + auditThreshold int32 + capacityBytes int64 + description string + fieldValue string + id string + merge bool + name string + resetTime string + timezone string + ) + cmd := &cobra.Command{ + Use: "update", + Short: "Update an existing ingest budget.", + Run: func(cmd *cobra.Command, args []string) { + updateIngestBudget(action, auditThreshold, capacityBytes, description, fieldValue, id, merge, + name, resetTime, timezone, client) + }, + } + cmd.Flags().StringVar(&action, "action", "", "Specify an action to take when ingest budget's capacity is reached."+ + "Supported values are either stopCollecting or keepCollecting.") + cmd.Flags().Int32Var(&auditThreshold, "auditThreshold", 1, "Specify a percentage of when an ingest budget's capacity usage is logged in the Audit Index") + cmd.Flags().Int64Var(&capacityBytes, "capacityBytes", 0, "Specify the capacity of the ingest budget in bytes.") + cmd.Flags().StringVar(&description, "description", "", "Specify a description for the ingest budget") + cmd.Flags().StringVar(&fieldValue, "fieldValue", "", "Specify the custom field value that is used to assign Collectors to the ingest budget") + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") + cmd.Flags().BoolVar(&merge, "merge", true, "If set to false it will overwrite the ingest budget configuration") + cmd.Flags().StringVar(&name, "name", "", "Specify a name for the ingest budget") + cmd.Flags().StringVar(&resetTime, "resetTime", "", "Specify the reset time of the ingest bidget in HH:MM format") + cmd.Flags().StringVar(&timezone, "timezone", "", "Specify the timezone of the reset time in IANA Time Zone format") + cmd.MarkFlagRequired("action") + cmd.MarkFlagRequired("capacityBytes") + cmd.MarkFlagRequired("fieldValue") + cmd.MarkFlagRequired("id") + cmd.MarkFlagRequired("name") + cmd.MarkFlagRequired("resetTime") + cmd.MarkFlagRequired("timezone") + return cmd +} + +func updateIngestBudget(action string, auditThreshold int32, capacityBytes int64, description string, fieldValue string, id string, merge bool, + name string, resetTime string, timezone string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.UpdateIngestBudget(types.IngestBudgetDefinition{ + Name: name, + FieldValue: fieldValue, + CapacityBytes: capacityBytes, + Timezone: timezone, + ResetTime: resetTime, + Description: description, + Action: action, + AuditThreshold: auditThreshold, + }, + id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/ingest_budgets_v2/create/create.go b/pkg/cmd/ingest_budgets_v2/create/create.go new file mode 100644 index 00000000..6fda70d0 --- /dev/null +++ b/pkg/cmd/ingest_budgets_v2/create/create.go @@ -0,0 +1,64 @@ +package create + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdIngestBudgetsV2Create(client *cip.APIClient) *cobra.Command { + var ( + action string + auditThreshold int32 + capacityBytes int64 + description string + scope string + name string + resetTime string + timezone string + ) + cmd := &cobra.Command{ + Use: "create", + Short: "Create a new ingest budget.", + Run: func(cmd *cobra.Command, args []string) { + createIngestBudgetV2(action, auditThreshold, capacityBytes, description, name, resetTime, scope, timezone, + client) + }, + } + cmd.Flags().StringVar(&action, "action", "", "Specify an action to take when ingest budget's capacity is reached."+ + "Supported values are either stopCollecting or keepCollecting.") + cmd.Flags().Int32Var(&auditThreshold, "auditThreshold", 1, "Specify a percentage of when an ingest budget's capacity usage is logged in the Audit Index") + cmd.Flags().Int64Var(&capacityBytes, "capacityBytes", 0, "Specify the capacity of the ingest budget in bytes.") + cmd.Flags().StringVar(&description, "description", "", "Specify a description for the ingest budget") + cmd.Flags().StringVar(&name, "name", "", "Specify a name for the ingest budget") + cmd.Flags().StringVar(&resetTime, "resetTime", "", "Specify the reset time of the ingest bidget in HH:MM format") + cmd.Flags().StringVar(&scope, "scope", "", "Specify a scope which will be used to identify the messages on which the budget needs to be applied") + cmd.Flags().StringVar(&timezone, "timezone", "", "Specify the timezone of the reset time in IANA Time Zone format") + cmd.MarkFlagRequired("action") + cmd.MarkFlagRequired("capacityBytes") + cmd.MarkFlagRequired("name") + cmd.MarkFlagRequired("resetTime") + cmd.MarkFlagRequired("scope") + cmd.MarkFlagRequired("timezone") + return cmd +} + +func createIngestBudgetV2(action string, auditThreshold int32, capacityBytes int64, description string, name string, + resetTime string, scope string, timezone string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.CreateIngestBudgetV2(types.IngestBudgetDefinitionV2{ + Name: name, + Scope: scope, + CapacityBytes: capacityBytes, + Timezone: timezone, + ResetTime: resetTime, + Description: description, + Action: action, + AuditThreshold: auditThreshold, + }) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/ingest_budgets_v2/delete/delete.go b/pkg/cmd/ingest_budgets_v2/delete/delete.go new file mode 100644 index 00000000..6739e4d7 --- /dev/null +++ b/pkg/cmd/ingest_budgets_v2/delete/delete.go @@ -0,0 +1,30 @@ +package delete + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdIngestBudgetsV2Delete(client *cip.APIClient) *cobra.Command { + var id string + cmd := &cobra.Command{ + Use: "delete", + Short: "Delete an ingest budget with the given identifier.", + Run: func(cmd *cobra.Command, args []string) { + deleteIngestBudgetV2(id, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") + cmd.MarkFlagRequired("id") + return cmd +} + +func deleteIngestBudgetV2(id string, client *cip.APIClient) { + httpResponse, errorResponse := client.DeleteIngestBudgetV2(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(nil, httpResponse, errorResponse, "The ingest budget was deleted successfully.") + } +} diff --git a/pkg/cmd/ingest_budgets_v2/get/get.go b/pkg/cmd/ingest_budgets_v2/get/get.go new file mode 100644 index 00000000..99848b55 --- /dev/null +++ b/pkg/cmd/ingest_budgets_v2/get/get.go @@ -0,0 +1,30 @@ +package get + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdIngestBudgetsV2Get(client *cip.APIClient) *cobra.Command { + var id string + cmd := &cobra.Command{ + Use: "get", + Short: "Get an ingest budget by the given identifier.", + Run: func(cmd *cobra.Command, args []string) { + getIngestBudgetV2(id, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") + cmd.MarkFlagRequired("id") + return cmd +} + +func getIngestBudgetV2(id string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.GetIngestBudgetV2(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/ingest-budgets-v2/ingest-budgets-v2.go b/pkg/cmd/ingest_budgets_v2/ingest_budgets_v2.go similarity index 74% rename from pkg/cmd/ingest-budgets-v2/ingest-budgets-v2.go rename to pkg/cmd/ingest_budgets_v2/ingest_budgets_v2.go index cd5001ac..99009c38 100644 --- a/pkg/cmd/ingest-budgets-v2/ingest-budgets-v2.go +++ b/pkg/cmd/ingest_budgets_v2/ingest_budgets_v2.go @@ -2,25 +2,26 @@ package ingest_budgets_v2 import ( "github.com/spf13/cobra" - NewCmdIngestBudgetsV2Create "github.com/wizedkyle/sumocli/pkg/cmd/ingest-budgets-v2/create" - NewCmdIngestBudgetsV2Delete "github.com/wizedkyle/sumocli/pkg/cmd/ingest-budgets-v2/delete" - NewCmdIngestBudgetsV2Get "github.com/wizedkyle/sumocli/pkg/cmd/ingest-budgets-v2/get" - NewCmdIngestBudgetsV2List "github.com/wizedkyle/sumocli/pkg/cmd/ingest-budgets-v2/list" - NewCmdIngestBudgetsV2Reset "github.com/wizedkyle/sumocli/pkg/cmd/ingest-budgets-v2/reset" - NewCmdIngestBudgetsV2Update "github.com/wizedkyle/sumocli/pkg/cmd/ingest-budgets-v2/update" + NewCmdIngestBudgetsV2Create "github.com/wizedkyle/sumocli/pkg/cmd/ingest_budgets_v2/create" + NewCmdIngestBudgetsV2Delete "github.com/wizedkyle/sumocli/pkg/cmd/ingest_budgets_v2/delete" + NewCmdIngestBudgetsV2Get "github.com/wizedkyle/sumocli/pkg/cmd/ingest_budgets_v2/get" + NewCmdIngestBudgetsV2List "github.com/wizedkyle/sumocli/pkg/cmd/ingest_budgets_v2/list" + NewCmdIngestBudgetsV2Reset "github.com/wizedkyle/sumocli/pkg/cmd/ingest_budgets_v2/reset" + NewCmdIngestBudgetsV2Update "github.com/wizedkyle/sumocli/pkg/cmd/ingest_budgets_v2/update" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdIngestBudgetsV2() *cobra.Command { +func NewCmdIngestBudgetsV2(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "ingest-budgets-v2", Short: "Manage ingest budgets (v2)", Long: "Ingest Budgets V2 provide you the ability to create and assign budgets to your log data by Fields instead of using a Field Value.", } - cmd.AddCommand(NewCmdIngestBudgetsV2Create.NewCmdIngestBudgetsV2Create()) - cmd.AddCommand(NewCmdIngestBudgetsV2Delete.NewCmdIngestBudgetsV2Delete()) - cmd.AddCommand(NewCmdIngestBudgetsV2Get.NewCmdIngestBudgetsV2Get()) - cmd.AddCommand(NewCmdIngestBudgetsV2List.NewCmdIngestBudgetsV2List()) - cmd.AddCommand(NewCmdIngestBudgetsV2Reset.NewCmdIngestBudgetsV2Reset()) - cmd.AddCommand(NewCmdIngestBudgetsV2Update.NewCmdIngestBudgetsV2Update()) + cmd.AddCommand(NewCmdIngestBudgetsV2Create.NewCmdIngestBudgetsV2Create(client)) + cmd.AddCommand(NewCmdIngestBudgetsV2Delete.NewCmdIngestBudgetsV2Delete(client)) + cmd.AddCommand(NewCmdIngestBudgetsV2Get.NewCmdIngestBudgetsV2Get(client)) + cmd.AddCommand(NewCmdIngestBudgetsV2List.NewCmdIngestBudgetsV2List(client)) + cmd.AddCommand(NewCmdIngestBudgetsV2Reset.NewCmdIngestBudgetsV2Reset(client)) + cmd.AddCommand(NewCmdIngestBudgetsV2Update.NewCmdIngestBudgetsV2Update(client)) return cmd } diff --git a/pkg/cmd/ingest_budgets_v2/list/list.go b/pkg/cmd/ingest_budgets_v2/list/list.go new file mode 100644 index 00000000..0a2fd524 --- /dev/null +++ b/pkg/cmd/ingest_budgets_v2/list/list.go @@ -0,0 +1,50 @@ +package list + +import ( + "github.com/antihax/optional" + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdIngestBudgetsV2List(client *cip.APIClient) *cobra.Command { + var limit int32 + cmd := &cobra.Command{ + Use: "list", + Short: "Get a list of all ingest budgets.", + Run: func(cmd *cobra.Command, args []string) { + listIngestBudgetsV2(limit, client) + }, + } + cmd.Flags().Int32Var(&limit, "limit", 100, "Specify the number of results to return maximum is 1000") + return cmd +} + +func listIngestBudgetsV2(limit int32, client *cip.APIClient) { + var options types.ListIngestBudgetV2Opts + var paginationToken string + options.Limit = optional.NewInt32(limit) + apiResponse, httpResponse, errorResponse := client.ListIngestBudgetsV2(&options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + paginationToken = apiResponse.Next + for paginationToken != "" { + apiResponse = listIngestBudgetsV2Pagination(client, options, paginationToken) + paginationToken = apiResponse.Next + } +} + +func listIngestBudgetsV2Pagination(client *cip.APIClient, options types.ListIngestBudgetV2Opts, token string) types.ListIngestBudgetsResponseV2 { + options.Token = optional.NewString(token) + apiResponse, httpResponse, errorResponse := client.ListIngestBudgetsV2(&options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } + return apiResponse +} diff --git a/pkg/cmd/ingest_budgets_v2/reset/reset.go b/pkg/cmd/ingest_budgets_v2/reset/reset.go new file mode 100644 index 00000000..b2ee68a2 --- /dev/null +++ b/pkg/cmd/ingest_budgets_v2/reset/reset.go @@ -0,0 +1,30 @@ +package reset + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdIngestBudgetsV2Reset(client *cip.APIClient) *cobra.Command { + var id string + cmd := &cobra.Command{ + Use: "reset", + Short: "Reset ingest budget's current usage to 0 before the scheduled reset time.", + Run: func(cmd *cobra.Command, args []string) { + resetIngestBudgetV2(id, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") + cmd.MarkFlagRequired("id") + return cmd +} + +func resetIngestBudgetV2(id string, client *cip.APIClient) { + httpResponse, errorResponse := client.ResetUsageV2(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(nil, httpResponse, errorResponse, "Ingest budget's usage was reset successfully.") + } +} diff --git a/pkg/cmd/ingest_budgets_v2/update/update.go b/pkg/cmd/ingest_budgets_v2/update/update.go new file mode 100644 index 00000000..5cf7ae74 --- /dev/null +++ b/pkg/cmd/ingest_budgets_v2/update/update.go @@ -0,0 +1,70 @@ +package update + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdIngestBudgetsV2Update(client *cip.APIClient) *cobra.Command { + var ( + action string + auditThreshold int32 + capacityBytes int64 + description string + id string + merge bool + name string + resetTime string + scope string + timezone string + ) + cmd := &cobra.Command{ + Use: "update", + Short: "Update an existing ingest budget.", + Run: func(cmd *cobra.Command, args []string) { + updateIngestBudgetV2(action, auditThreshold, capacityBytes, description, id, merge, name, + resetTime, scope, timezone, client) + }, + } + cmd.Flags().StringVar(&action, "action", "", "Specify an action to take when ingest budget's capacity is reached."+ + "Supported values are either stopCollecting or keepCollecting.") + cmd.Flags().Int32Var(&auditThreshold, "auditThreshold", 1, "Specify a percentage of when an ingest budget's capacity usage is logged in the Audit Index") + cmd.Flags().Int64Var(&capacityBytes, "capacityBytes", 0, "Specify the capacity of the ingest budget in bytes.") + cmd.Flags().StringVar(&description, "description", "", "Specify a description for the ingest budget") + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the ingest budget") + cmd.Flags().BoolVar(&merge, "merge", true, "If set to false it will overwrite the ingest budget configuration") + cmd.Flags().StringVar(&name, "name", "", "Specify a name for the ingest budget") + cmd.Flags().StringVar(&resetTime, "resetTime", "", "Specify the reset time of the ingest bidget in HH:MM format") + cmd.Flags().StringVar(&scope, "scope", "", "Specify a scope which will be used to identify the messages on which the budget needs to be applied") + cmd.Flags().StringVar(&timezone, "timezone", "", "Specify the timezone of the reset time in IANA Time Zone format") + cmd.MarkFlagRequired("action") + cmd.MarkFlagRequired("capacityBytes") + cmd.MarkFlagRequired("id") + cmd.MarkFlagRequired("name") + cmd.MarkFlagRequired("resetTime") + cmd.MarkFlagRequired("scope") + cmd.MarkFlagRequired("timezone") + return cmd +} + +func updateIngestBudgetV2(action string, auditThreshold int32, capacityBytes int64, description string, id string, merge bool, + name string, resetTime string, scope string, timezone string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.UpdateIngestBudgetV2(types.IngestBudgetDefinitionV2{ + Name: name, + Scope: scope, + CapacityBytes: capacityBytes, + Timezone: timezone, + ResetTime: resetTime, + Description: description, + Action: action, + AuditThreshold: auditThreshold, + }, + id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/lookup-tables/create/create.go b/pkg/cmd/lookup-tables/create/create.go deleted file mode 100644 index a3a3cfe5..00000000 --- a/pkg/cmd/lookup-tables/create/create.go +++ /dev/null @@ -1,110 +0,0 @@ -package create - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "strings" -) - -func NewCmdLookupTablesCreate() *cobra.Command { - var ( - description string - fieldNames string - fieldTypes string - primaryKeys string - ttl int - sizeLimitAction string - name string - parentFolderId string - ) - - cmd := &cobra.Command{ - Use: "create", - Short: "Create a new lookup table by providing a schema and specifying its configuration.", - Run: func(cmd *cobra.Command, args []string) { - createLookupTable(description, fieldNames, fieldTypes, primaryKeys, ttl, sizeLimitAction, name, parentFolderId) - }, - } - cmd.Flags().StringVar(&description, "description", "", "Specify a description for the lookup table") - cmd.Flags().StringVar(&fieldNames, "fieldNames", "", "List of field names (they need to be comma separated e.g. test,test1,test2") - cmd.Flags().StringVar(&fieldTypes, "fieldTypes", "", "List of field types that align with the fieldNames "+ - "(they need to be comma separated e.g. string,boolean,int). The following fieldTypes can be specified: "+ - "boolean, int, long, double, string") - cmd.Flags().StringVar(&primaryKeys, "primaryKeys", "", "List of field names that make up the primary key for the"+ - "lookup table (they need to be comma separated e.g. name1,name2,name3). ") - cmd.Flags().IntVar(&ttl, "ttl", 0, "A time to live for each entry in the lookup table (in minutes). "+ - "365 days is the maximum ttl, leaving the ttl as 0 means that the records will not expire automatically.") - cmd.Flags().StringVar(&sizeLimitAction, "sizeLimitAction", "StopIncomingMessages", "The action that needs to be taken"+ - "when the size limit is reached for the table. The possible values can be StopIncomingMessages (default) or DeleteOldData.") - cmd.Flags().StringVar(&name, "name", "", "Specify the name of the lookup table") - cmd.Flags().StringVar(&parentFolderId, "parentFolderId", "", "Specify the parent folder path identifier of the lookup table in the Library") - - cmd.MarkFlagRequired("description") - cmd.MarkFlagRequired("fieldNames") - cmd.MarkFlagRequired("fieldTypes") - cmd.MarkFlagRequired("primaryKeys") - cmd.MarkFlagRequired("name") - cmd.MarkFlagRequired("parentFolderId") - return cmd -} - -func createLookupTable(description string, fieldNames string, fieldTypes string, primaryKeys string, - ttl int, sizeLimitAction string, name string, parentFolderId string) { - var createLookupTableResponse api.LookupTableResponse - log := logging.GetConsoleLogger() - requestBodySchema := &api.CreateLookupTableRequest{ - Description: description, - PrimaryKeys: strings.Split(primaryKeys, ","), - Ttl: ttl, - SizeLimitAction: sizeLimitAction, - Name: name, - ParentFolderId: parentFolderId, - } - fieldNameSlice := strings.Split(fieldNames, ",") - fieldTypeSlice := strings.Split(fieldTypes, ",") - for i := range fieldNameSlice { - fieldAddition := api.LookupTableFields{ - FieldName: fieldNameSlice[i], - FieldType: fieldTypeSlice[i], - } - requestBodySchema.Fields = append(requestBodySchema.Fields, fieldAddition) - i++ - } - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("error marshalling request body") - } - requestUrl := "/v1/lookupTables" - client, request := factory.NewHttpRequestWithBody("POST", requestUrl, requestBody) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &createLookupTableResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - createLookupTableResponseJson, err := json.MarshalIndent(createLookupTableResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal lookupTableResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(createLookupTableResponseJson)) - } -} diff --git a/pkg/cmd/lookup-tables/delete-data/delete-data.go b/pkg/cmd/lookup-tables/delete-data/delete-data.go deleted file mode 100644 index 4a95791c..00000000 --- a/pkg/cmd/lookup-tables/delete-data/delete-data.go +++ /dev/null @@ -1,59 +0,0 @@ -package delete_data - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdLookupTablesDeleteData() *cobra.Command { - var id string - - cmd := &cobra.Command{ - Use: "delete-data", - Short: "Delete all data from a lookup table.", - Run: func(cmd *cobra.Command, args []string) { - deleteLookupTableData(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the lookup table to delete data from") - cmd.MarkFlagRequired("id") - return cmd -} - -func deleteLookupTableData(id string) { - var deleteDataResponse api.LookupTableRequestId - log := logging.GetConsoleLogger() - requestUrl := "/v1/lookupTables/" + id + "/truncate" - client, request := factory.NewHttpRequest("POST", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &deleteDataResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - deleteLookupTableDataResponseJson, err := json.MarshalIndent(deleteDataResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal lookupTableResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(deleteLookupTableDataResponseJson)) - } -} diff --git a/pkg/cmd/lookup-tables/delete-row/delete-row.go b/pkg/cmd/lookup-tables/delete-row/delete-row.go deleted file mode 100644 index 1eb2476f..00000000 --- a/pkg/cmd/lookup-tables/delete-row/delete-row.go +++ /dev/null @@ -1,74 +0,0 @@ -package delete_row - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "strings" -) - -func NewCmdLookupTablesDeleteRow() *cobra.Command { - var ( - id string - columnNames string - columnValues string - ) - - cmd := &cobra.Command{ - Use: "delete-row", - Short: "Delete a row from lookup table by giving primary key. The complete set of primary key fields of the lookup table should be provided.", - Run: func(cmd *cobra.Command, args []string) { - deleteLookupTableRow(id, columnNames, columnValues) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the lookup table") - cmd.Flags().StringVar(&columnNames, "columnNames", "", "List of primary key column names "+ - "(they need to be comma separated e.g. field1,field2,field3)") - cmd.Flags().StringVar(&columnValues, "columnValues", "", "List of values "+ - "(they need to be comma separated e.g. value1,value2,value3).") - cmd.MarkFlagRequired("id") - cmd.MarkFlagRequired("columnNames") - cmd.MarkFlagRequired("columnValues") - return cmd -} - -func deleteLookupTableRow(id string, columnNames string, columnValues string) { - log := logging.GetConsoleLogger() - requestBodySchema := &api.LookupTableRemoveRowRequest{} - columnNameSlice := strings.Split(columnNames, ",") - columnValueSlice := strings.Split(columnValues, ",") - for i := range columnNameSlice { - columnAddition := api.LookupTableRow{ - ColumnName: columnNameSlice[i], - ColumnValue: columnValueSlice[i], - } - requestBodySchema.PrimaryKey = append(requestBodySchema.PrimaryKey, columnAddition) - i++ - } - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("error marshalling request body") - } - requestUrl := "/v1/lookupTables/" + id + "/deleteTableRow" - client, request := factory.NewHttpRequestWithBody("PUT", requestUrl, requestBody) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - if response.StatusCode == 204 { - fmt.Println("Row deleted successfully") - } else { - factory.HttpError(response.StatusCode, responseBody, log) - } -} diff --git a/pkg/cmd/lookup-tables/delete/delete.go b/pkg/cmd/lookup-tables/delete/delete.go deleted file mode 100644 index 6d3e6383..00000000 --- a/pkg/cmd/lookup-tables/delete/delete.go +++ /dev/null @@ -1,52 +0,0 @@ -package delete - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdLookupTablesDelete() *cobra.Command { - var id string - - cmd := &cobra.Command{ - Use: "delete", - Short: "Delete a lookup table completely.", - Run: func(cmd *cobra.Command, args []string) { - deleteLookupTable(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the lookup table to delete") - cmd.MarkFlagRequired("id") - return cmd -} - -func deleteLookupTable(id string) { - log := logging.GetConsoleLogger() - requestUrl := "/v1/lookupTables/" + id - client, request := factory.NewHttpRequest("DELETE", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - if response.StatusCode != 204 { - var responseError api.ResponseError - err := json.Unmarshal(responseBody, &responseError) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - } else { - fmt.Println("Lookup table was deleted.") - } -} diff --git a/pkg/cmd/lookup-tables/edit/edit.go b/pkg/cmd/lookup-tables/edit/edit.go deleted file mode 100644 index 4abd9af8..00000000 --- a/pkg/cmd/lookup-tables/edit/edit.go +++ /dev/null @@ -1,79 +0,0 @@ -package edit - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdLookupTablesEdit() *cobra.Command { - var ( - description string - id string - ttl int - sizeLimitAction string - ) - - cmd := &cobra.Command{ - Use: "edit", - Short: "Edits the configuration of the given lookup table", - Run: func(cmd *cobra.Command, args []string) { - editLookupTable(description, id, ttl, sizeLimitAction) - }, - } - cmd.Flags().StringVar(&description, "description", "", "Specify a description for the lookup table") - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the lookup table to edit") - cmd.Flags().IntVar(&ttl, "ttl", 0, "A time to live for each entry in the lookup table (in minutes). "+ - "365 days is the maximum ttl, leaving the ttl as 0 means that the records will not expire automatically.") - cmd.Flags().StringVar(&sizeLimitAction, "sizeLimitAction", "StopIncomingMessages", "The action that needs to be taken"+ - "when the size limit is reached for the table. The possible values can be StopIncomingMessages (default) or DeleteOldData.") - cmd.MarkFlagRequired("description") - cmd.MarkFlagRequired("id") - return cmd -} - -func editLookupTable(description string, id string, ttl int, sizeLimitAction string) { - var editLookupTableResponse api.LookupTableResponse - log := logging.GetConsoleLogger() - requestBodySchema := &api.EditLookupTable{ - Description: description, - Ttl: ttl, - SizeLimitAction: sizeLimitAction, - } - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("error marshalling request body") - } - requestUrl := "/v1/lookupTables/" + id - client, request := factory.NewHttpRequestWithBody("PUT", requestUrl, requestBody) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &editLookupTableResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - editLookupTableResponseJson, err := json.MarshalIndent(editLookupTableResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal lookupTableResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(editLookupTableResponseJson)) - } -} diff --git a/pkg/cmd/lookup-tables/empty/empty.go b/pkg/cmd/lookup-tables/empty/empty.go deleted file mode 100644 index 979df9e2..00000000 --- a/pkg/cmd/lookup-tables/empty/empty.go +++ /dev/null @@ -1,70 +0,0 @@ -package empty - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdLookupTableEmpty() *cobra.Command { - var ( - id string - jsonFormat bool - ) - - cmd := &cobra.Command{ - Use: "empty", - Short: "Delete all data from a lookup table.", - Run: func(cmd *cobra.Command, args []string) { - emptyLookupTable(id, jsonFormat) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the lookup table to empty") - cmd.Flags().BoolVar(&jsonFormat, "jsonFormat", false, "Set to true if you want the output to be formatted JSON") - cmd.MarkFlagRequired("id") - return cmd -} - -func emptyLookupTable(id string, jsonFormat bool) { - var emptyLookupTableRequest api.LookupTableRequestId - log := logging.GetConsoleLogger() - requestUrl := "/v1/lookupTables/" + id + "/truncate" - client, request := factory.NewHttpRequest("POST", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &emptyLookupTableRequest) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - if jsonFormat == true { - emptyLookupTableRequestJson, err := json.MarshalIndent(emptyLookupTableRequest, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - fmt.Print(string(emptyLookupTableRequestJson)) - } else { - emptyLookupTableRequestJson, err := json.Marshal(emptyLookupTableRequest) - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - fmt.Println(string(emptyLookupTableRequestJson)) - } - } -} diff --git a/pkg/cmd/lookup-tables/get/get.go b/pkg/cmd/lookup-tables/get/get.go deleted file mode 100644 index 8229b5bc..00000000 --- a/pkg/cmd/lookup-tables/get/get.go +++ /dev/null @@ -1,58 +0,0 @@ -package get - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdLookupTablesGet() *cobra.Command { - var id string - cmd := &cobra.Command{ - Use: "get", - Short: "Gets a Sumo Logic lookup table based on the given identifier", - Run: func(cmd *cobra.Command, args []string) { - getLookupTable(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the lookup table you want to retrieve") - cmd.MarkFlagRequired("id") - return cmd -} - -func getLookupTable(id string) { - var lookupTableResponse api.LookupTableResponse - log := logging.GetConsoleLogger() - requestUrl := "/v1/lookupTables/" + id - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &lookupTableResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - lookupTableResponseJson, err := json.MarshalIndent(lookupTableResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal lookupTableResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(lookupTableResponseJson)) - } -} diff --git a/pkg/cmd/lookup-tables/insert-row/insert-row.go b/pkg/cmd/lookup-tables/insert-row/insert-row.go deleted file mode 100644 index 0cc7f378..00000000 --- a/pkg/cmd/lookup-tables/insert-row/insert-row.go +++ /dev/null @@ -1,76 +0,0 @@ -package insert_row - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "strings" -) - -func NewCmdLookupTablesInsertRow() *cobra.Command { - var ( - id string - columnNames string - columnValues string - ) - - cmd := &cobra.Command{ - Use: "insert-row", - Short: "Insert or update a row of a lookup table with the given identifier.", - Long: " new row is inserted if the primary key does not exist already, otherwise the existing row with the specified primary key is updated. All the fields of the lookup table are required and will be updated to the given values. " + - "In case a field is not specified then it will be assumed to be set to null.", - Run: func(cmd *cobra.Command, args []string) { - insertLookupTableRow(id, columnNames, columnValues) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the lookup table") - cmd.Flags().StringVar(&columnNames, "columnNames", "", "List of column names "+ - "(they need to be comma separated e.g. field1,field2,field3)") - cmd.Flags().StringVar(&columnValues, "columnValues", "", "List of values "+ - "(they need to be comma separated e.g. value1,value2,value3).") - cmd.MarkFlagRequired("id") - cmd.MarkFlagRequired("columnNames") - cmd.MarkFlagRequired("columnValues") - return cmd -} - -func insertLookupTableRow(id string, columnNames string, columnValues string) { - log := logging.GetConsoleLogger() - requestBodySchema := &api.LookupTableRowRequest{} - columnNameSlice := strings.Split(columnNames, ",") - columnValueSlice := strings.Split(columnValues, ",") - for i := range columnNameSlice { - columnAddition := api.LookupTableRow{ - ColumnName: columnNameSlice[i], - ColumnValue: columnValueSlice[i], - } - requestBodySchema.Row = append(requestBodySchema.Row, columnAddition) - i++ - } - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("error marshalling request body") - } - requestUrl := "/v1/lookupTables/" + id + "/row" - client, request := factory.NewHttpRequestWithBody("PUT", requestUrl, requestBody) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - if response.StatusCode == 204 { - fmt.Println("Row updated successfully") - } else { - factory.HttpError(response.StatusCode, responseBody, log) - } -} diff --git a/pkg/cmd/lookup-tables/job-status/job-status.go b/pkg/cmd/lookup-tables/job-status/job-status.go deleted file mode 100644 index 2942e5fa..00000000 --- a/pkg/cmd/lookup-tables/job-status/job-status.go +++ /dev/null @@ -1,70 +0,0 @@ -package job_status - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdLookupTableJobStatus() *cobra.Command { - var ( - jobId string - jsonFormat bool - ) - - cmd := &cobra.Command{ - Use: "job-status", - Short: "Retrieve the status of a previously made request using sumocli lookup-tables upload or sumocli lookup-tables empty", - Run: func(cmd *cobra.Command, args []string) { - getLookupTableJobStatus(jobId, jsonFormat) - }, - } - cmd.Flags().StringVar(&jobId, "jobId", "", "Specify the Job ID to get the status for (returned from running sumocli lookup-tables upload or sumocli lookup-tables empty") - cmd.Flags().BoolVar(&jsonFormat, "jsonFormat", false, "Set to true if you want the output to be formatted JSON") - cmd.MarkFlagRequired("jobId") - return cmd -} - -func getLookupTableJobStatus(jobId string, jsonFormat bool) { - var statusResponse api.LookupTableStatusResponse - log := logging.GetConsoleLogger() - requestUrl := "/v1/lookupTables/jobs/" + jobId + "/status" - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &statusResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - if jsonFormat == true { - statusResponseJson, err := json.MarshalIndent(statusResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - fmt.Print(string(statusResponseJson)) - } else { - statusResponseJson, err := json.Marshal(statusResponse) - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - fmt.Println(string(statusResponseJson)) - } - } -} diff --git a/pkg/cmd/lookup_tables/create/create.go b/pkg/cmd/lookup_tables/create/create.go new file mode 100644 index 00000000..a7289149 --- /dev/null +++ b/pkg/cmd/lookup_tables/create/create.go @@ -0,0 +1,67 @@ +package create + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdLookupTablesCreate(client *cip.APIClient) *cobra.Command { + var ( + description string + fieldNames []string + fieldTypes []string + primaryKeys []string + ttl int32 + sizeLimitAction string + name string + parentFolderId string + ) + cmd := &cobra.Command{ + Use: "create", + Short: "Create a new lookup table by providing a schema and specifying its configuration.", + Run: func(cmd *cobra.Command, args []string) { + createLookupTable(description, fieldNames, fieldTypes, primaryKeys, ttl, sizeLimitAction, name, + parentFolderId, client) + }, + } + cmd.Flags().StringVar(&description, "description", "", "Specify a description for the lookup table") + cmd.Flags().StringSliceVar(&fieldNames, "fieldNames", []string{}, "List of field names (they need to be comma separated e.g. test,test1,test2") + cmd.Flags().StringSliceVar(&fieldTypes, "fieldTypes", []string{}, "List of field types that align with the fieldNames "+ + "(they need to be comma separated e.g. string,boolean,int). The following fieldTypes can be specified: "+ + "boolean, int, long, double, string") + cmd.Flags().StringSliceVar(&primaryKeys, "primaryKeys", []string{}, "List of field names that make up the primary key for the"+ + "lookup table (they need to be comma separated e.g. name1,name2,name3). ") + cmd.Flags().Int32Var(&ttl, "ttl", 0, "A time to live for each entry in the lookup table (in minutes). "+ + "365 days is the maximum ttl, leaving the ttl as 0 means that the records will not expire automatically.") + cmd.Flags().StringVar(&sizeLimitAction, "sizeLimitAction", "StopIncomingMessages", "The action that needs to be taken "+ + "when the size limit is reached for the table. The possible values can be StopIncomingMessages (default) or DeleteOldData.") + cmd.Flags().StringVar(&name, "name", "", "Specify the name of the lookup table") + cmd.Flags().StringVar(&parentFolderId, "parentFolderId", "", "Specify the parent folder path identifier of the lookup table in the Library") + cmd.MarkFlagRequired("description") + cmd.MarkFlagRequired("fieldNames") + cmd.MarkFlagRequired("fieldTypes") + cmd.MarkFlagRequired("primaryKeys") + cmd.MarkFlagRequired("name") + cmd.MarkFlagRequired("parentFolderId") + return cmd +} + +func createLookupTable(description string, fieldNames []string, fieldTypes []string, primaryKeys []string, + ttl int32, sizeLimitAction string, name string, parentFolderId string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.CreateTable(types.LookupTableDefinition{ + Description: description, + Fields: cmdutils.GenerateLookupTableFields(fieldNames, fieldTypes), + PrimaryKeys: primaryKeys, + Ttl: ttl, + SizeLimitAction: sizeLimitAction, + Name: name, + ParentFolderId: parentFolderId, + }) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/lookup_tables/delete-data/delete-data.go b/pkg/cmd/lookup_tables/delete-data/delete-data.go new file mode 100644 index 00000000..33e5b063 --- /dev/null +++ b/pkg/cmd/lookup_tables/delete-data/delete-data.go @@ -0,0 +1,30 @@ +package delete_data + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdLookupTablesDeleteData(client *cip.APIClient) *cobra.Command { + var id string + cmd := &cobra.Command{ + Use: "delete-data", + Short: "Delete all data from a lookup table.", + Run: func(cmd *cobra.Command, args []string) { + deleteLookupTableData(id, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the lookup table to delete data from") + cmd.MarkFlagRequired("id") + return cmd +} + +func deleteLookupTableData(id string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.TruncateTable(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/lookup_tables/delete-row/delete-row.go b/pkg/cmd/lookup_tables/delete-row/delete-row.go new file mode 100644 index 00000000..921720aa --- /dev/null +++ b/pkg/cmd/lookup_tables/delete-row/delete-row.go @@ -0,0 +1,44 @@ +package delete_row + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdLookupTablesDeleteRow(client *cip.APIClient) *cobra.Command { + var ( + id string + columnNames []string + columnValues []string + ) + cmd := &cobra.Command{ + Use: "delete-row", + Short: "Delete a row from lookup table by providing the primary key. The complete set of primary key fields of the lookup table should be provided.", + Run: func(cmd *cobra.Command, args []string) { + deleteLookupTableRow(id, columnNames, columnValues, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the lookup table") + cmd.Flags().StringSliceVar(&columnNames, "columnNames", []string{}, "List of primary key column names "+ + "(they need to be comma separated e.g. field1,field2,field3)") + cmd.Flags().StringSliceVar(&columnValues, "columnValues", []string{}, "List of values "+ + "(they need to be comma separated e.g. value1,value2,value3).") + cmd.MarkFlagRequired("id") + cmd.MarkFlagRequired("columnNames") + cmd.MarkFlagRequired("columnValues") + return cmd +} + +func deleteLookupTableRow(id string, columnNames []string, columnValues []string, client *cip.APIClient) { + httpResponse, errorResponse := client.DeleteTableRow(types.RowDeleteDefinition{ + PrimaryKey: cmdutils.GenerateLookupTableColumns(columnNames, columnValues), + }, + id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(nil, httpResponse, errorResponse, "Row deleted successfully.") + } +} diff --git a/pkg/cmd/lookup_tables/delete/delete.go b/pkg/cmd/lookup_tables/delete/delete.go new file mode 100644 index 00000000..cae02e88 --- /dev/null +++ b/pkg/cmd/lookup_tables/delete/delete.go @@ -0,0 +1,30 @@ +package delete + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdLookupTablesDelete(client *cip.APIClient) *cobra.Command { + var id string + cmd := &cobra.Command{ + Use: "delete", + Short: "Delete a lookup table completely.", + Run: func(cmd *cobra.Command, args []string) { + deleteLookupTable(id, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the lookup table to delete") + cmd.MarkFlagRequired("id") + return cmd +} + +func deleteLookupTable(id string, client *cip.APIClient) { + httpResponse, errorResponse := client.DeleteTable(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(nil, httpResponse, errorResponse, "Lookup table deleted successfully.") + } +} diff --git a/pkg/cmd/lookup_tables/get/get.go b/pkg/cmd/lookup_tables/get/get.go new file mode 100644 index 00000000..7a9175e6 --- /dev/null +++ b/pkg/cmd/lookup_tables/get/get.go @@ -0,0 +1,30 @@ +package get + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdLookupTablesGet(client *cip.APIClient) *cobra.Command { + var id string + cmd := &cobra.Command{ + Use: "get", + Short: "Gets a Sumo Logic lookup table based on the given identifier", + Run: func(cmd *cobra.Command, args []string) { + getLookupTable(id, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the lookup table you want to retrieve") + cmd.MarkFlagRequired("id") + return cmd +} + +func getLookupTable(id string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.LookupTableById(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/lookup_tables/insert-row/insert-row.go b/pkg/cmd/lookup_tables/insert-row/insert-row.go new file mode 100644 index 00000000..6b7f3b43 --- /dev/null +++ b/pkg/cmd/lookup_tables/insert-row/insert-row.go @@ -0,0 +1,46 @@ +package insert_row + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdLookupTablesInsertRow(client *cip.APIClient) *cobra.Command { + var ( + id string + columnNames []string + columnValues []string + ) + cmd := &cobra.Command{ + Use: "insert-row", + Short: "Insert or update a row of a lookup table with the given identifier.", + Long: "A new row is inserted if the primary key does not exist already, otherwise the existing row with the specified primary key is updated. All the fields of the lookup table are required and will be updated to the given values. " + + "In case a field is not specified then it will be assumed to be set to null.", + Run: func(cmd *cobra.Command, args []string) { + insertLookupTableRow(id, columnNames, columnValues, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the lookup table") + cmd.Flags().StringSliceVar(&columnNames, "columnNames", []string{}, "List of column names "+ + "(they need to be comma separated e.g. field1,field2,field3)") + cmd.Flags().StringSliceVar(&columnValues, "columnValues", []string{}, "List of values "+ + "(they need to be comma separated e.g. value1,value2,value3).") + cmd.MarkFlagRequired("id") + cmd.MarkFlagRequired("columnNames") + cmd.MarkFlagRequired("columnValues") + return cmd +} + +func insertLookupTableRow(id string, columnNames []string, columnValues []string, client *cip.APIClient) { + httpResponse, errorResponse := client.UpdateTableRow(types.RowUpdateDefinition{ + Row: cmdutils.GenerateLookupTableColumns(columnNames, columnValues), + }, + id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(nil, httpResponse, errorResponse, "Row updated successfully.") + } +} diff --git a/pkg/cmd/lookup_tables/job-status/job-status.go b/pkg/cmd/lookup_tables/job-status/job-status.go new file mode 100644 index 00000000..7d23dc2f --- /dev/null +++ b/pkg/cmd/lookup_tables/job-status/job-status.go @@ -0,0 +1,30 @@ +package job_status + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdLookupTableJobStatus(client *cip.APIClient) *cobra.Command { + var jobId string + cmd := &cobra.Command{ + Use: "job-status", + Short: "Retrieve the status of a previously made request using sumocli lookup-tables upload or sumocli lookup-tables empty", + Run: func(cmd *cobra.Command, args []string) { + getLookupTableJobStatus(jobId, client) + }, + } + cmd.Flags().StringVar(&jobId, "jobId", "", "Specify the Job ID to get the status for (returned from running sumocli lookup-tables upload or sumocli lookup-tables empty") + cmd.MarkFlagRequired("jobId") + return cmd +} + +func getLookupTableJobStatus(jobId string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.RequestJobStatus(jobId) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/lookup-tables/lookup-tables.go b/pkg/cmd/lookup_tables/lookup_tables.go similarity index 52% rename from pkg/cmd/lookup-tables/lookup-tables.go rename to pkg/cmd/lookup_tables/lookup_tables.go index 5b54b701..4d00133f 100644 --- a/pkg/cmd/lookup-tables/lookup-tables.go +++ b/pkg/cmd/lookup_tables/lookup_tables.go @@ -2,31 +2,32 @@ package lookup_tables import ( "github.com/spf13/cobra" - cmdLookupTablesCreate "github.com/wizedkyle/sumocli/pkg/cmd/lookup-tables/create" - cmdLookupTablesDelete "github.com/wizedkyle/sumocli/pkg/cmd/lookup-tables/delete" - cmdLookupTablesDeleteData "github.com/wizedkyle/sumocli/pkg/cmd/lookup-tables/delete-data" - cmdLookupTablesDeleteRow "github.com/wizedkyle/sumocli/pkg/cmd/lookup-tables/delete-row" - cmdLookupTablesEdit "github.com/wizedkyle/sumocli/pkg/cmd/lookup-tables/edit" - cmdLookupTablesEmpty "github.com/wizedkyle/sumocli/pkg/cmd/lookup-tables/empty" - cmdLookupTablesGet "github.com/wizedkyle/sumocli/pkg/cmd/lookup-tables/get" - cmdLookupTablesInsertRow "github.com/wizedkyle/sumocli/pkg/cmd/lookup-tables/insert-row" - cmdLookupTablesJobStatus "github.com/wizedkyle/sumocli/pkg/cmd/lookup-tables/job-status" + cmdLookupTablesCreate "github.com/wizedkyle/sumocli/pkg/cmd/lookup_tables/create" + cmdLookupTablesDelete "github.com/wizedkyle/sumocli/pkg/cmd/lookup_tables/delete" + cmdLookupTablesDeleteData "github.com/wizedkyle/sumocli/pkg/cmd/lookup_tables/delete-data" + cmdLookupTablesDeleteRow "github.com/wizedkyle/sumocli/pkg/cmd/lookup_tables/delete-row" + cmdLookupTablesGet "github.com/wizedkyle/sumocli/pkg/cmd/lookup_tables/get" + cmdLookupTablesInsertRow "github.com/wizedkyle/sumocli/pkg/cmd/lookup_tables/insert-row" + cmdLookupTablesJobStatus "github.com/wizedkyle/sumocli/pkg/cmd/lookup_tables/job-status" + cmdLookupTablesUpdate "github.com/wizedkyle/sumocli/pkg/cmd/lookup_tables/update" + cmdLookupTablesUpload "github.com/wizedkyle/sumocli/pkg/cmd/lookup_tables/upload" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdLookupTables() *cobra.Command { +func NewCmdLookupTables(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "lookup-tables", Short: "Manage lookup tables", Long: "Commands that allow you to manage Lookup Tables in your Sumo Logic tenant", } - cmd.AddCommand(cmdLookupTablesCreate.NewCmdLookupTablesCreate()) - cmd.AddCommand(cmdLookupTablesDelete.NewCmdLookupTablesDelete()) - cmd.AddCommand(cmdLookupTablesDeleteData.NewCmdLookupTablesDeleteData()) - cmd.AddCommand(cmdLookupTablesDeleteRow.NewCmdLookupTablesDeleteRow()) - cmd.AddCommand(cmdLookupTablesEdit.NewCmdLookupTablesEdit()) - cmd.AddCommand(cmdLookupTablesEmpty.NewCmdLookupTableEmpty()) - cmd.AddCommand(cmdLookupTablesGet.NewCmdLookupTablesGet()) - cmd.AddCommand(cmdLookupTablesInsertRow.NewCmdLookupTablesInsertRow()) - cmd.AddCommand(cmdLookupTablesJobStatus.NewCmdLookupTableJobStatus()) + cmd.AddCommand(cmdLookupTablesCreate.NewCmdLookupTablesCreate(client)) + cmd.AddCommand(cmdLookupTablesDelete.NewCmdLookupTablesDelete(client)) + cmd.AddCommand(cmdLookupTablesDeleteData.NewCmdLookupTablesDeleteData(client)) + cmd.AddCommand(cmdLookupTablesDeleteRow.NewCmdLookupTablesDeleteRow(client)) + cmd.AddCommand(cmdLookupTablesUpdate.NewCmdLookupTablesEdit(client)) + cmd.AddCommand(cmdLookupTablesGet.NewCmdLookupTablesGet(client)) + cmd.AddCommand(cmdLookupTablesInsertRow.NewCmdLookupTablesInsertRow(client)) + cmd.AddCommand(cmdLookupTablesJobStatus.NewCmdLookupTableJobStatus(client)) + cmd.AddCommand(cmdLookupTablesUpload.NewCmdLookupTablesUpload(client)) return cmd } diff --git a/pkg/cmd/lookup_tables/update/update.go b/pkg/cmd/lookup_tables/update/update.go new file mode 100644 index 00000000..0de6362f --- /dev/null +++ b/pkg/cmd/lookup_tables/update/update.go @@ -0,0 +1,47 @@ +package update + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" +) + +func NewCmdLookupTablesEdit(client *cip.APIClient) *cobra.Command { + var ( + description string + id string + ttl int32 + sizeLimitAction string + ) + cmd := &cobra.Command{ + Use: "update", + Short: "Edits the configuration of the given lookup table", + Run: func(cmd *cobra.Command, args []string) { + updateLookupTable(description, id, ttl, sizeLimitAction, client) + }, + } + cmd.Flags().StringVar(&description, "description", "", "Specify a description for the lookup table") + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the lookup table to edit") + cmd.Flags().Int32Var(&ttl, "ttl", 0, "A time to live for each entry in the lookup table (in minutes). "+ + "365 days is the maximum ttl, leaving the ttl as 0 means that the records will not expire automatically.") + cmd.Flags().StringVar(&sizeLimitAction, "sizeLimitAction", "StopIncomingMessages", "The action that needs to be taken"+ + "when the size limit is reached for the table. The possible values can be StopIncomingMessages (default) or DeleteOldData.") + cmd.MarkFlagRequired("description") + cmd.MarkFlagRequired("id") + return cmd +} + +func updateLookupTable(description string, id string, ttl int32, sizeLimitAction string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.UpdateTable(types.LookupUpdateDefinition{ + Ttl: ttl, + Description: description, + SizeLimitAction: sizeLimitAction, + }, + id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/lookup_tables/upload/upload.go b/pkg/cmd/lookup_tables/upload/upload.go new file mode 100644 index 00000000..98078cb0 --- /dev/null +++ b/pkg/cmd/lookup_tables/upload/upload.go @@ -0,0 +1,52 @@ +package upload + +import ( + "fmt" + "github.com/antihax/optional" + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" + "os" +) + +func NewCmdLookupTablesUpload(client *cip.APIClient) *cobra.Command { + var ( + fileEncoding string + fileLocation string + id string + merge bool + ) + cmd := &cobra.Command{ + Use: "upload", + Short: "Create a request to populate a lookup table with a CSV file", + Run: func(cmd *cobra.Command, args []string) { + uploadData(fileEncoding, fileLocation, id, merge, client) + }, + } + cmd.Flags().StringVar(&fileEncoding, "fileEncoding", "UTF-8", "Encoding of the CSV file being uploaded.") + cmd.Flags().StringVar(&fileLocation, "fileLocation", "", "File path of the CSV file.") + cmd.Flags().StringVar(&id, "id", "", "Id of the lookup table to upload the file to.") + cmd.Flags().BoolVar(&merge, "merge", false, "If this is set to true file contents will be merged with existing data in the lookup table. "+ + "By default the data with the same primary keys will be updated while the reset of the rows will be appended.") + cmd.MarkFlagRequired("fileLocation") + cmd.MarkFlagRequired("id") + return cmd +} + +func uploadData(fileEncoding string, fileLocation string, id string, merge bool, client *cip.APIClient) { + var options types.LookupTableUploadFileOpts + options.FileEncoding = optional.NewString(fileEncoding) + options.Merge = optional.NewBool(merge) + file, err := os.Open(fileLocation) + if err != nil { + fmt.Println("File location (" + fileLocation + ") couldn't be opened, please the file exists.") + os.Exit(1) + } + apiResponse, httpResponse, errorResponse := client.UploadFile(file, id, &options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/partitions/cancel-retention-update/cancel-retention-update.go b/pkg/cmd/partitions/cancel-retention-update/cancel-retention-update.go deleted file mode 100644 index 672e1c6e..00000000 --- a/pkg/cmd/partitions/cancel-retention-update/cancel-retention-update.go +++ /dev/null @@ -1,52 +0,0 @@ -package cancel_retention_update - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdPartitionsCancelRetentionUpdate() *cobra.Command { - var id string - - cmd := &cobra.Command{ - Use: "cancel-retention-update", - Short: "Cancel update to retention of a partition for which retention was updated previously using sumocli partitions update and the reduceRetentionPeriodImmediately parameter was set to false", - Run: func(cmd *cobra.Command, args []string) { - cancelRetentionUpdate(id) - }, - } - cmd.Flags().StringVar(&id, "id", "", "Specify the id of the partition") - cmd.MarkFlagRequired("id") - return cmd -} - -func cancelRetentionUpdate(id string) { - log := logging.GetConsoleLogger() - requestUrl := "/v1/partitions/" + id + "/cancelRetentionUpdate" - client, request := factory.NewHttpRequest("POST", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - if response.StatusCode != 204 { - var responseError api.ResponseError - err := json.Unmarshal(responseBody, &responseError) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - } else { - fmt.Println("The retention update was cancelled successfully.") - } -} diff --git a/pkg/cmd/partitions/cancel_retention_update/cancel_retention_update.go b/pkg/cmd/partitions/cancel_retention_update/cancel_retention_update.go new file mode 100644 index 00000000..c224fb57 --- /dev/null +++ b/pkg/cmd/partitions/cancel_retention_update/cancel_retention_update.go @@ -0,0 +1,30 @@ +package cancel_retention_update + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdPartitionsCancelRetentionUpdate(client *cip.APIClient) *cobra.Command { + var id string + cmd := &cobra.Command{ + Use: "cancel-retention-update", + Short: "Cancel update to retention of a partition for which retention was updated previously using sumocli partitions update and the reduceRetentionPeriodImmediately parameter was set to false", + Run: func(cmd *cobra.Command, args []string) { + cancelRetentionUpdate(id, client) + }, + } + cmd.Flags().StringVar(&id, "id", "", "Specify the id of the partition") + cmd.MarkFlagRequired("id") + return cmd +} + +func cancelRetentionUpdate(id string, client *cip.APIClient) { + httpResponse, errorResponse := client.CancelRetentionUpdate(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(nil, httpResponse, errorResponse, "The retention update was cancelled successfully.") + } +} diff --git a/pkg/cmd/partitions/create/create.go b/pkg/cmd/partitions/create/create.go index 4f2d77fe..5338134b 100644 --- a/pkg/cmd/partitions/create/create.go +++ b/pkg/cmd/partitions/create/create.go @@ -1,36 +1,32 @@ package created import ( - "encoding/json" - "fmt" "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdPartitionCreate() *cobra.Command { +func NewCmdPartitionCreate(client *cip.APIClient) *cobra.Command { var ( name string routingExpression string analyticsTier string - retentionPeriod int + retentionPeriod int32 isCompliant bool ) - cmd := &cobra.Command{ Use: "create", Short: "Create a new partition.", Run: func(cmd *cobra.Command, args []string) { - createPartition(name, routingExpression, analyticsTier, retentionPeriod, isCompliant) + createPartition(name, routingExpression, analyticsTier, retentionPeriod, isCompliant, client) }, } cmd.Flags().StringVar(&name, "name", "", "Specify a name for the partition") cmd.Flags().StringVar(&routingExpression, "routingExpression", "", "Specify the query that defines the data to be included in the partition") cmd.Flags().StringVar(&analyticsTier, "analyticsTier", "continuous", "Specify the Data Tier where the data in the partition will reside. "+ "Possible values are continuous, frequent, infrequent.") - cmd.Flags().IntVar(&retentionPeriod, "retentionPeriod", -1, "Specify the number of days to retain data in the partition. "+ + cmd.Flags().Int32Var(&retentionPeriod, "retentionPeriod", -1, "Specify the number of days to retain data in the partition. "+ "-1 specifies that the default value for the account is used.") cmd.Flags().BoolVar(&isCompliant, "isCompliant", false, "Set to true if the partition is compliant") cmd.MarkFlagRequired("name") @@ -38,46 +34,18 @@ func NewCmdPartitionCreate() *cobra.Command { return cmd } -func createPartition(name string, routingExpression string, analyticsTier string, retentionPeriod int, isCompliant bool) { - var partitionsResponse api.Partitions - log := logging.GetConsoleLogger() - requestBodySchema := &api.CreatePartition{ +func createPartition(name string, routingExpression string, analyticsTier string, retentionPeriod int32, isCompliant bool, + client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.CreatePartition(types.CreatePartitionDefinition{ Name: name, RoutingExpression: routingExpression, AnalyticsTier: analyticsTier, RetentionPeriod: retentionPeriod, IsCompliant: isCompliant, - } - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("error marshalling request body") - } - requestUrl := "/v1/partitions" - client, request := factory.NewHttpRequestWithBody("POST", requestUrl, requestBody) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &partitionsResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - partitionsResponseJson, err := json.MarshalIndent(partitionsResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal lookupTableResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) + }) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) } else { - fmt.Println(string(partitionsResponseJson)) + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } } diff --git a/pkg/cmd/partitions/decommission/decommission.go b/pkg/cmd/partitions/decommission/decommission.go index c9460931..eb3eec39 100644 --- a/pkg/cmd/partitions/decommission/decommission.go +++ b/pkg/cmd/partitions/decommission/decommission.go @@ -1,23 +1,18 @@ package decommission import ( - "encoding/json" - "fmt" "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdPartitionsDecommission() *cobra.Command { +func NewCmdPartitionsDecommission(client *cip.APIClient) *cobra.Command { var id string - cmd := &cobra.Command{ Use: "decommission", Short: "Decommission a partition with the given identifier from the organization.", Run: func(cmd *cobra.Command, args []string) { - decommissionPartition(id) + decommissionPartition(id, client) }, } cmd.Flags().StringVar(&id, "id", "", "Specify the id of the partition") @@ -25,28 +20,11 @@ func NewCmdPartitionsDecommission() *cobra.Command { return cmd } -func decommissionPartition(id string) { - log := logging.GetConsoleLogger() - requestUrl := "/v1/partitions/" + id + "/decommission" - client, request := factory.NewHttpRequest("POST", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - if response.StatusCode != 204 { - var responseError api.ResponseError - err := json.Unmarshal(responseBody, &responseError) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } +func decommissionPartition(id string, client *cip.APIClient) { + httpResponse, errorResponse := client.DecommissionPartition(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) } else { - fmt.Println("The partition was decommissioned successfully.") + cmdutils.Output(nil, httpResponse, errorResponse, "The partition was decommissioned successfully.") } } diff --git a/pkg/cmd/partitions/get/get.go b/pkg/cmd/partitions/get/get.go index 285cf55d..f327e30d 100644 --- a/pkg/cmd/partitions/get/get.go +++ b/pkg/cmd/partitions/get/get.go @@ -1,23 +1,18 @@ package get import ( - "encoding/json" - "fmt" "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdPartitionsGet() *cobra.Command { +func NewCmdPartitionsGet(client *cip.APIClient) *cobra.Command { var id string - cmd := &cobra.Command{ Use: "get", Short: "Get a partition with the given identifier from the organization.", Run: func(cmd *cobra.Command, args []string) { - getPartition(id) + getPartition(id, client) }, } cmd.Flags().StringVar(&id, "id", "", "Specify the id of the partition") @@ -25,35 +20,11 @@ func NewCmdPartitionsGet() *cobra.Command { return cmd } -func getPartition(id string) { - var partitionsResponse api.Partitions - log := logging.GetConsoleLogger() - requestUrl := "/v1/partitions/" + id - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &partitionsResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - partitionsResponseJson, err := json.MarshalIndent(partitionsResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) +func getPartition(id string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.GetPartition(id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) } else { - fmt.Println(string(partitionsResponseJson)) + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } } diff --git a/pkg/cmd/partitions/list/list.go b/pkg/cmd/partitions/list/list.go index 40fbd28a..587e184a 100644 --- a/pkg/cmd/partitions/list/list.go +++ b/pkg/cmd/partitions/list/list.go @@ -1,69 +1,56 @@ package list import ( - "encoding/json" - "fmt" + "github.com/antihax/optional" "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "net/url" - "strconv" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdPartitionsList() *cobra.Command { +func NewCmdPartitionsList(client *cip.APIClient) *cobra.Command { var ( - limit int - viewTypes string + limit int32 + viewTypes []string ) - cmd := &cobra.Command{ Use: "list", Short: "Get a list of all partitions in the organization.", Run: func(cmd *cobra.Command, args []string) { - listPartitions(limit, viewTypes) + listPartitions(limit, viewTypes, client) }, } - cmd.Flags().IntVar(&limit, "limit", 100, "Specify the number of results to return maximum is 1000") - cmd.Flags().StringVar(&viewTypes, "viewTypes", "", "Specify the type of partitions to retrieve. "+ + cmd.Flags().Int32Var(&limit, "limit", 100, "Specify the number of results to return maximum is 1000") + cmd.Flags().StringSliceVar(&viewTypes, "viewTypes", []string{}, "Specify the type of partitions to retrieve. "+ "Valid values are: DefaultView, Partition, and AuditIndex. You can add multiple types for example DefaultView,Partition.") return cmd } -func listPartitions(limit int, viewTypes string) { - var partitionsResponse api.GetPartitions - log := logging.GetConsoleLogger() - requestUrl := "/v1/partitions" - client, request := factory.NewHttpRequest("GET", requestUrl) - query := url.Values{} - query.Add("limit", strconv.Itoa(limit)) - query.Add("viewTypes", viewTypes) - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &partitionsResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") +func listPartitions(limit int32, viewTypes []string, client *cip.APIClient) { + var options types.PartitionOpts + var paginationToken string + options.Limit = optional.NewInt32(limit) + options.ViewTypes = optional.NewInterface(viewTypes) + apiResponse, httpResponse, errorResponse := client.ListPartitions(&options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } - - partitionsResponseJson, err := json.MarshalIndent(partitionsResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal response") + paginationToken = apiResponse.Next + for paginationToken != "" { + apiResponse = listPartitionsPagination(client, options, paginationToken) + paginationToken = apiResponse.Next } +} - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) +func listPartitionsPagination(client *cip.APIClient, options types.PartitionOpts, token string) types.ListPartitionsResponse { + options.Token = optional.NewString(token) + apiResponse, httpResponse, errorResponse := client.ListPartitions(&options) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) } else { - fmt.Println(string(partitionsResponseJson)) + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } + return apiResponse } diff --git a/pkg/cmd/partitions/partitions.go b/pkg/cmd/partitions/partitions.go index 6ed6075c..74a03cab 100644 --- a/pkg/cmd/partitions/partitions.go +++ b/pkg/cmd/partitions/partitions.go @@ -2,25 +2,26 @@ package partitions import ( "github.com/spf13/cobra" - NewCmdPartitionsCancelRetentionUpdate "github.com/wizedkyle/sumocli/pkg/cmd/partitions/cancel-retention-update" + NewCmdPartitionsCancelRetentionUpdate "github.com/wizedkyle/sumocli/pkg/cmd/partitions/cancel_retention_update" NewCmdPartitionsCreate "github.com/wizedkyle/sumocli/pkg/cmd/partitions/create" NewCmdPartitionsDecommission "github.com/wizedkyle/sumocli/pkg/cmd/partitions/decommission" NewCmdPartitionsGet "github.com/wizedkyle/sumocli/pkg/cmd/partitions/get" NewCmdPartitionsList "github.com/wizedkyle/sumocli/pkg/cmd/partitions/list" NewCmdPartitionsUpdate "github.com/wizedkyle/sumocli/pkg/cmd/partitions/update" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdPartitions() *cobra.Command { +func NewCmdPartitions(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "partitions", Short: "Manage partitions", Long: "Creating a Partition allows you to improve search performance by searching over a smaller number of messages.", } - cmd.AddCommand(NewCmdPartitionsCancelRetentionUpdate.NewCmdPartitionsCancelRetentionUpdate()) - cmd.AddCommand(NewCmdPartitionsCreate.NewCmdPartitionCreate()) - cmd.AddCommand(NewCmdPartitionsDecommission.NewCmdPartitionsDecommission()) - cmd.AddCommand(NewCmdPartitionsGet.NewCmdPartitionsGet()) - cmd.AddCommand(NewCmdPartitionsList.NewCmdPartitionsList()) - cmd.AddCommand(NewCmdPartitionsUpdate.NewCmdPartitionUpdate()) + cmd.AddCommand(NewCmdPartitionsCancelRetentionUpdate.NewCmdPartitionsCancelRetentionUpdate(client)) + cmd.AddCommand(NewCmdPartitionsCreate.NewCmdPartitionCreate(client)) + cmd.AddCommand(NewCmdPartitionsDecommission.NewCmdPartitionsDecommission(client)) + cmd.AddCommand(NewCmdPartitionsGet.NewCmdPartitionsGet(client)) + cmd.AddCommand(NewCmdPartitionsList.NewCmdPartitionsList(client)) + cmd.AddCommand(NewCmdPartitionsUpdate.NewCmdPartitionUpdate(client)) return cmd } diff --git a/pkg/cmd/partitions/update/update.go b/pkg/cmd/partitions/update/update.go index c1d0e5b4..f2326b47 100644 --- a/pkg/cmd/partitions/update/update.go +++ b/pkg/cmd/partitions/update/update.go @@ -1,33 +1,29 @@ package update import ( - "encoding/json" - "fmt" "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdPartitionUpdate() *cobra.Command { +func NewCmdPartitionUpdate(client *cip.APIClient) *cobra.Command { var ( id string - retentionPeriod int + retentionPeriod int32 reduceRetentionPeriodImmediately bool isCompliant bool routingExpression string ) - cmd := &cobra.Command{ Use: "update", Short: "Update an existing partition in the organization.", Run: func(cmd *cobra.Command, args []string) { - updatePartition(id, retentionPeriod, reduceRetentionPeriodImmediately, isCompliant, routingExpression) + updatePartition(id, retentionPeriod, reduceRetentionPeriodImmediately, isCompliant, routingExpression, client) }, } cmd.Flags().StringVar(&id, "id", "", "Specify the id of the partition") - cmd.Flags().IntVar(&retentionPeriod, "retentionPeriod", -1, "Specify the number of days to retain data in the partition. "+ + cmd.Flags().Int32Var(&retentionPeriod, "retentionPeriod", -1, "Specify the number of days to retain data in the partition. "+ "-1 specifies that the default value for the account is used.") cmd.Flags().BoolVar(&reduceRetentionPeriodImmediately, "reduceRetentionPeriodImmediately", false, "This is required if the newly specified retentionPeriod is less than the existing retention period. "+ "A value of true says that data between the existing retention period and the new retention period should be deleted immediately. "+ @@ -38,46 +34,18 @@ func NewCmdPartitionUpdate() *cobra.Command { return cmd } -func updatePartition(id string, retentionPeriod int, reduceRetentionPeriodImmediately bool, isCompliant bool, - routingExpression string) { - var partitionsResponse api.Partitions - log := logging.GetConsoleLogger() - requestBodySchema := &api.UpdatePartition{ +func updatePartition(id string, retentionPeriod int32, reduceRetentionPeriodImmediately bool, isCompliant bool, + routingExpression string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.UpdatePartition(types.UpdatePartitionDefinition{ RetentionPeriod: retentionPeriod, ReduceRetentionPeriodImmediately: reduceRetentionPeriodImmediately, IsCompliant: isCompliant, RoutingExpression: routingExpression, - } - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("error marshalling request body") - } - requestUrl := "/v1/partitions/" + id - client, request := factory.NewHttpRequestWithBody("PUT", requestUrl, requestBody) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &partitionsResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - partitionsResponseJson, err := json.MarshalIndent(partitionsResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal lookupTableResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) + }, + id) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) } else { - fmt.Println(string(partitionsResponseJson)) + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } } diff --git a/pkg/cmd/roles/assign/assign.go b/pkg/cmd/roles/assign/assign.go index d9f161c7..695c925f 100644 --- a/pkg/cmd/roles/assign/assign.go +++ b/pkg/cmd/roles/assign/assign.go @@ -1,13 +1,12 @@ package assign import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdRoleAssign(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdRoleAssign(client *cip.APIClient) *cobra.Command { var ( roleId string userId string @@ -16,7 +15,7 @@ func NewCmdRoleAssign(client *cip.APIClient, log *zerolog.Logger) *cobra.Command Use: "assign", Short: "Assigns the specified Sumo Logic user to the role.", Run: func(cmd *cobra.Command, args []string) { - assignRoleToUser(client, roleId, userId, log) + assignRoleToUser(client, roleId, userId) }, } cmd.Flags().StringVar(&roleId, "roleId", "", "Specify the identifier of the role to assign.") @@ -26,10 +25,10 @@ func NewCmdRoleAssign(client *cip.APIClient, log *zerolog.Logger) *cobra.Command return cmd } -func assignRoleToUser(client *cip.APIClient, roleId string, userId string, log *zerolog.Logger) { +func assignRoleToUser(client *cip.APIClient, roleId string, userId string) { apiResponse, httpResponse, errorResponse := client.AssignRoleToUser(roleId, userId) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to assign role to user") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/roles/create/create.go b/pkg/cmd/roles/create/create.go index 467b7319..00c57ea6 100644 --- a/pkg/cmd/roles/create/create.go +++ b/pkg/cmd/roles/create/create.go @@ -1,14 +1,14 @@ package create import ( - "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdRoleCreate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdRoleCreate(client *cip.APIClient) *cobra.Command { var ( name string description string @@ -21,7 +21,7 @@ func NewCmdRoleCreate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command Use: "create", Short: "Creates a Sumo Logic role", Run: func(cmd *cobra.Command, args []string) { - createRole(client, name, description, filter, users, capabilities, autofill, log) + createRole(client, name, description, filter, users, capabilities, autofill) }, } cmd.Flags().StringVar(&name, "name", "", "Name of the role.") @@ -35,7 +35,7 @@ func NewCmdRoleCreate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command } func createRole(client *cip.APIClient, name string, description string, filter string, users []string, - capabilities []string, autofill bool, log *zerolog.Logger) { + capabilities []string, autofill bool) { for i, capability := range capabilities { if cmdutils.ValidateCapabilities(capability) == false { log.Error().Msg(capability + " is not a valid Sumo Logic role capability.") @@ -52,7 +52,7 @@ func createRole(client *cip.APIClient, name string, description string, filter s } apiResponse, httpResponse, errorResponse := client.CreateRole(body) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to create role") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/roles/delete/delete.go b/pkg/cmd/roles/delete/delete.go index ae777a13..af8dc670 100644 --- a/pkg/cmd/roles/delete/delete.go +++ b/pkg/cmd/roles/delete/delete.go @@ -1,19 +1,18 @@ package delete import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdRoleDelete(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdRoleDelete(client *cip.APIClient) *cobra.Command { var id string cmd := &cobra.Command{ Use: "delete", Short: "Deletes a Sumo Logic role", Run: func(cmd *cobra.Command, args []string) { - deleteRole(client, id, log) + deleteRole(client, id) }, } cmd.Flags().StringVar(&id, "id", "", "Specify the identifier of the role to delete.") @@ -21,10 +20,10 @@ func NewCmdRoleDelete(client *cip.APIClient, log *zerolog.Logger) *cobra.Command return cmd } -func deleteRole(client *cip.APIClient, id string, log *zerolog.Logger) { +func deleteRole(client *cip.APIClient, id string) { httpResponse, errorResponse := client.DeleteRole(id) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to delete role") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(nil, httpResponse, errorResponse, "Role was deleted successfully") } diff --git a/pkg/cmd/roles/get/get.go b/pkg/cmd/roles/get/get.go index a76d201a..d0d7c773 100644 --- a/pkg/cmd/roles/get/get.go +++ b/pkg/cmd/roles/get/get.go @@ -1,19 +1,18 @@ package get import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdRoleGet(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdRoleGet(client *cip.APIClient) *cobra.Command { var id string cmd := &cobra.Command{ Use: "get", Short: "Gets a Sumo Logic role information", Run: func(cmd *cobra.Command, args []string) { - getRole(client, id, log) + getRole(client, id) }, } cmd.Flags().StringVar(&id, "id", "", "Specify the id of the role to get") @@ -21,10 +20,10 @@ func NewCmdRoleGet(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { return cmd } -func getRole(client *cip.APIClient, id string, log *zerolog.Logger) { +func getRole(client *cip.APIClient, id string) { apiResponse, httpResponse, errorResponse := client.GetRole(id) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to get role") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/roles/list/list.go b/pkg/cmd/roles/list/list.go index 32239fa3..361d3e62 100644 --- a/pkg/cmd/roles/list/list.go +++ b/pkg/cmd/roles/list/list.go @@ -2,14 +2,13 @@ package list import ( "github.com/antihax/optional" - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdRoleList(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdRoleList(client *cip.APIClient) *cobra.Command { var ( limit int32 name string @@ -19,7 +18,7 @@ func NewCmdRoleList(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { Use: "list", Short: "Lists Sumo Logic roles", Run: func(cmd *cobra.Command, args []string) { - listRoles(client, limit, name, sortBy, log) + listRoles(client, limit, name, sortBy) }, } cmd.Flags().Int32Var(&limit, "limit", 100, "Specify the number of results, this is set to 100 by default.") @@ -28,7 +27,7 @@ func NewCmdRoleList(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { return cmd } -func listRoles(client *cip.APIClient, limit int32, name string, sortBy bool, log *zerolog.Logger) { +func listRoles(client *cip.APIClient, limit int32, name string, sortBy bool) { var options types.ListRolesOpts var paginationToken string options.Limit = optional.NewInt32(limit) @@ -40,22 +39,22 @@ func listRoles(client *cip.APIClient, limit int32, name string, sortBy bool, log } apiResponse, httpResponse, errorResponse := client.ListRoles(&options) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to list roles") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } paginationToken = apiResponse.Next for paginationToken != "" { - apiResponse = listRolesPagination(client, options, paginationToken, log) + apiResponse = listRolesPagination(client, options, paginationToken) paginationToken = apiResponse.Next } } -func listRolesPagination(client *cip.APIClient, options types.ListRolesOpts, token string, log *zerolog.Logger) types.ListRoleModelsResponse { +func listRolesPagination(client *cip.APIClient, options types.ListRolesOpts, token string) types.ListRoleModelsResponse { options.Token = optional.NewString(token) apiResponse, httpResponse, errorResponse := client.ListRoles(&options) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to list roles") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/roles/remove/remove.go b/pkg/cmd/roles/remove/remove.go index 527fb7d9..ed5f01f4 100644 --- a/pkg/cmd/roles/remove/remove.go +++ b/pkg/cmd/roles/remove/remove.go @@ -1,13 +1,12 @@ package remove import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdRoleRemoveUser(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdRoleRemoveUser(client *cip.APIClient) *cobra.Command { var ( roleId string userId string @@ -16,7 +15,7 @@ func NewCmdRoleRemoveUser(client *cip.APIClient, log *zerolog.Logger) *cobra.Com Use: "remove user", Short: "Removes the specified Sumo Logic user from the role.", Run: func(cmd *cobra.Command, args []string) { - removeRoleFromUser(client, roleId, userId, log) + removeRoleFromUser(client, roleId, userId) }, } cmd.Flags().StringVar(&roleId, "roleId", "", "Specify the identifier of the role.") @@ -26,10 +25,10 @@ func NewCmdRoleRemoveUser(client *cip.APIClient, log *zerolog.Logger) *cobra.Com return cmd } -func removeRoleFromUser(client *cip.APIClient, roleId string, userId string, log *zerolog.Logger) { +func removeRoleFromUser(client *cip.APIClient, roleId string, userId string) { httpResponse, errorResponse := client.RemoveRoleFromUser(roleId, userId) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to remove role from user") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(nil, httpResponse, errorResponse, "User: "+userId+" was removed from role: "+roleId) } diff --git a/pkg/cmd/roles/roles.go b/pkg/cmd/roles/roles.go index d86695f4..ee825f46 100644 --- a/pkg/cmd/roles/roles.go +++ b/pkg/cmd/roles/roles.go @@ -1,7 +1,6 @@ package roles import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" cmdRoleAssign "github.com/wizedkyle/sumocli/pkg/cmd/roles/assign" cmdRoleCreate "github.com/wizedkyle/sumocli/pkg/cmd/roles/create" @@ -13,19 +12,19 @@ import ( "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdRole(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdRole(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "roles ", Short: "Manage roles", Long: "Commands that allow you to manage roles in your Sumo Logic tenant", } - cmd.AddCommand(cmdRoleAssign.NewCmdRoleAssign(client, log)) - cmd.AddCommand(cmdRoleCreate.NewCmdRoleCreate(client, log)) - cmd.AddCommand(cmdRoleDelete.NewCmdRoleDelete(client, log)) - cmd.AddCommand(cmdRoleGet.NewCmdRoleGet(client, log)) - cmd.AddCommand(cmdRoleList.NewCmdRoleList(client, log)) - cmd.AddCommand(cmdRoleRemove.NewCmdRoleRemoveUser(client, log)) - cmd.AddCommand(cmdRoleUpdate.NewCmdRoleUpdate(client, log)) + cmd.AddCommand(cmdRoleAssign.NewCmdRoleAssign(client)) + cmd.AddCommand(cmdRoleCreate.NewCmdRoleCreate(client)) + cmd.AddCommand(cmdRoleDelete.NewCmdRoleDelete(client)) + cmd.AddCommand(cmdRoleGet.NewCmdRoleGet(client)) + cmd.AddCommand(cmdRoleList.NewCmdRoleList(client)) + cmd.AddCommand(cmdRoleRemove.NewCmdRoleRemoveUser(client)) + cmd.AddCommand(cmdRoleUpdate.NewCmdRoleUpdate(client)) return cmd } diff --git a/pkg/cmd/roles/update/update.go b/pkg/cmd/roles/update/update.go index bdb89a6e..cf5574ed 100644 --- a/pkg/cmd/roles/update/update.go +++ b/pkg/cmd/roles/update/update.go @@ -1,14 +1,14 @@ package update import ( - "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdRoleUpdate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdRoleUpdate(client *cip.APIClient) *cobra.Command { var ( id string name string @@ -22,7 +22,7 @@ func NewCmdRoleUpdate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command Use: "update", Short: "Updates a Sumo Logic role.", Run: func(cmd *cobra.Command, args []string) { - updateRole(client, id, name, description, filter, users, capabilities, autofill, log) + updateRole(client, id, name, description, filter, users, capabilities, autofill) }, } cmd.Flags().StringVar(&id, "id", "", "Specify the id of the role to update.") @@ -38,7 +38,7 @@ func NewCmdRoleUpdate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command } func updateRole(client *cip.APIClient, id string, name string, description string, filter string, users []string, - capabilities []string, autofill bool, log *zerolog.Logger) { + capabilities []string, autofill bool) { for i, capability := range capabilities { if cmdutils.ValidateCapabilities(capability) == false { log.Error().Msg(capability + " is not a valid Sumo Logic role capability.") @@ -55,7 +55,7 @@ func updateRole(client *cip.APIClient, id string, name string, description strin } apiResponse, httpResponse, errorResponse := client.UpdateRole(body, id) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to update role") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/root/root.go b/pkg/cmd/root/root.go index 7ec6208c..126d9682 100644 --- a/pkg/cmd/root/root.go +++ b/pkg/cmd/root/root.go @@ -8,18 +8,18 @@ import ( appsCmd "github.com/wizedkyle/sumocli/pkg/cmd/apps" archiveIngestion "github.com/wizedkyle/sumocli/pkg/cmd/archive-ingestion" collectorCmd "github.com/wizedkyle/sumocli/pkg/cmd/collectors" + ConfigureCmd "github.com/wizedkyle/sumocli/pkg/cmd/configure" contentCmd "github.com/wizedkyle/sumocli/pkg/cmd/content" dashboardsCmd "github.com/wizedkyle/sumocli/pkg/cmd/dashboards" - dynamicParsingCmd "github.com/wizedkyle/sumocli/pkg/cmd/dynamic-parsing" - fieldExtractionRulesCmd "github.com/wizedkyle/sumocli/pkg/cmd/field-extraction-rules" - fieldManagement "github.com/wizedkyle/sumocli/pkg/cmd/field-management" + dynamicParsingCmd "github.com/wizedkyle/sumocli/pkg/cmd/dynamic_parsing" + fieldExtractionRulesCmd "github.com/wizedkyle/sumocli/pkg/cmd/field_extraction_rules" + fieldManagement "github.com/wizedkyle/sumocli/pkg/cmd/field_management" foldersCmd "github.com/wizedkyle/sumocli/pkg/cmd/folders" - healthEventsCmd "github.com/wizedkyle/sumocli/pkg/cmd/health-events" - ingestBudgetsCmd "github.com/wizedkyle/sumocli/pkg/cmd/ingest-budgets" - ingestBudgetsV2Cmd "github.com/wizedkyle/sumocli/pkg/cmd/ingest-budgets-v2" + healthEventsCmd "github.com/wizedkyle/sumocli/pkg/cmd/health_events" + ingestBudgetsCmd "github.com/wizedkyle/sumocli/pkg/cmd/ingest_budgets" + ingestBudgetsV2Cmd "github.com/wizedkyle/sumocli/pkg/cmd/ingest_budgets_v2" liveTailCmd "github.com/wizedkyle/sumocli/pkg/cmd/live-tail" - loginCmd "github.com/wizedkyle/sumocli/pkg/cmd/login" - lookupTablesCmd "github.com/wizedkyle/sumocli/pkg/cmd/lookup-tables" + lookupTablesCmd "github.com/wizedkyle/sumocli/pkg/cmd/lookup_tables" monitorsCmd "github.com/wizedkyle/sumocli/pkg/cmd/monitors" partitionsCmd "github.com/wizedkyle/sumocli/pkg/cmd/partitions" passwordPolicyCmd "github.com/wizedkyle/sumocli/pkg/cmd/password-policy" @@ -27,12 +27,11 @@ import ( roleCmd "github.com/wizedkyle/sumocli/pkg/cmd/roles" samlCmd "github.com/wizedkyle/sumocli/pkg/cmd/saml" scheduledViewsCmd "github.com/wizedkyle/sumocli/pkg/cmd/scheduled-views" - serviceAllowlistCmd "github.com/wizedkyle/sumocli/pkg/cmd/service-allowlist" + serviceAllowlistCmd "github.com/wizedkyle/sumocli/pkg/cmd/service_allowlist" sourcesCmd "github.com/wizedkyle/sumocli/pkg/cmd/sources" tokensCmd "github.com/wizedkyle/sumocli/pkg/cmd/tokens" usersCmd "github.com/wizedkyle/sumocli/pkg/cmd/users" "github.com/wizedkyle/sumocli/pkg/cmd/version" - "github.com/wizedkyle/sumocli/pkg/logging" ) func NewCmdRoot() *cobra.Command { @@ -44,36 +43,35 @@ func NewCmdRoot() *cobra.Command { TraverseChildren: true, } client := config.GetSumoLogicSDKConfig() - log := logging.GetLogger() // Add subcommands - cmd.AddCommand(accountCmd.NewCmdAccount(client, log)) - cmd.AddCommand(accessKeysCmd.NewCmdAccessKeys(client, log)) - cmd.AddCommand(appsCmd.NewCmdApps(client, log)) - cmd.AddCommand(archiveIngestion.NewCmdArchiveIngestion(client, log)) - cmd.AddCommand(collectorCmd.NewCmdCollectors()) - cmd.AddCommand(contentCmd.NewCmdContent()) - cmd.AddCommand(dashboardsCmd.NewCmdDashboards()) - cmd.AddCommand(dynamicParsingCmd.NewCmdDynamicParsing()) - cmd.AddCommand(fieldExtractionRulesCmd.NewCmdFieldExtractionRules()) - cmd.AddCommand(fieldManagement.NewCmdFieldManagement()) - cmd.AddCommand(foldersCmd.NewCmdFolders(client, log)) - cmd.AddCommand(healthEventsCmd.NewCmdHealthEvents()) - cmd.AddCommand(ingestBudgetsCmd.NewCmdIngestBudgets()) - cmd.AddCommand(ingestBudgetsV2Cmd.NewCmdIngestBudgetsV2()) + cmd.AddCommand(accountCmd.NewCmdAccount(client)) + cmd.AddCommand(accessKeysCmd.NewCmdAccessKeys(client)) + cmd.AddCommand(appsCmd.NewCmdApps(client)) + cmd.AddCommand(archiveIngestion.NewCmdArchiveIngestion(client)) + cmd.AddCommand(collectorCmd.NewCmdCollectors(client)) + cmd.AddCommand(contentCmd.NewCmdContent(client)) + cmd.AddCommand(dashboardsCmd.NewCmdDashboards(client)) + cmd.AddCommand(dynamicParsingCmd.NewCmdDynamicParsing(client)) + cmd.AddCommand(fieldExtractionRulesCmd.NewCmdFieldExtractionRules(client)) + cmd.AddCommand(fieldManagement.NewCmdFieldManagement(client)) + cmd.AddCommand(foldersCmd.NewCmdFolders(client)) + cmd.AddCommand(healthEventsCmd.NewCmdHealthEvents(client)) + cmd.AddCommand(ingestBudgetsCmd.NewCmdIngestBudgets(client)) + cmd.AddCommand(ingestBudgetsV2Cmd.NewCmdIngestBudgetsV2(client)) cmd.AddCommand(liveTailCmd.NewCmdLiveTail()) - cmd.AddCommand(loginCmd.NewCmdLogin()) - cmd.AddCommand(lookupTablesCmd.NewCmdLookupTables()) + cmd.AddCommand(ConfigureCmd.NewCmdConfigure()) + cmd.AddCommand(lookupTablesCmd.NewCmdLookupTables(client)) cmd.AddCommand(monitorsCmd.NewCmdMonitors()) - cmd.AddCommand(partitionsCmd.NewCmdPartitions()) + cmd.AddCommand(partitionsCmd.NewCmdPartitions(client)) cmd.AddCommand(passwordPolicyCmd.NewCmdPasswordPolicy()) cmd.AddCommand(permissionsCmd.NewCmdPermissions()) - cmd.AddCommand(roleCmd.NewCmdRole(client, log)) + cmd.AddCommand(roleCmd.NewCmdRole(client)) cmd.AddCommand(samlCmd.NewCmdSaml()) cmd.AddCommand(scheduledViewsCmd.NewCmdScheduledViews()) - cmd.AddCommand(serviceAllowlistCmd.NewCmdServiceAllowlist()) - cmd.AddCommand(sourcesCmd.NewCmdSources(client, log)) - cmd.AddCommand(tokensCmd.NewCmdTokens(client, log)) - cmd.AddCommand(usersCmd.NewCmdUser(client, log)) + cmd.AddCommand(serviceAllowlistCmd.NewCmdServiceAllowlist(client)) + cmd.AddCommand(sourcesCmd.NewCmdSources(client)) + cmd.AddCommand(tokensCmd.NewCmdTokens(client)) + cmd.AddCommand(usersCmd.NewCmdUser(client)) cmd.AddCommand(version.NewCmdVersion()) // Add global, persistent flags - these apply for all commands and their subcommands diff --git a/pkg/cmd/service-allowlist/add/add.go b/pkg/cmd/service-allowlist/add/add.go deleted file mode 100644 index b774e77f..00000000 --- a/pkg/cmd/service-allowlist/add/add.go +++ /dev/null @@ -1,74 +0,0 @@ -package add - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdServiceAllowlistAdd() *cobra.Command { - var ( - cidr string - description string - ) - - cmd := &cobra.Command{ - Use: "add", - Short: "Add CIDR notations and/or IP addresses to the allowlist of the organization if not already there.", - Long: "When service allowlisting functionality is enabled, CIDRs/IP addresses that are allowlisted will have access to Sumo Logic and/or content sharing.", - Run: func(cmd *cobra.Command, args []string) { - addServiceAllowlistCidr(cidr, description) - }, - } - cmd.Flags().StringVar(&cidr, "cidr", "", "Specify the IP address to add in CIDR format") - cmd.Flags().StringVar(&description, "description", "", "Specify the description for the IP address") - cmd.MarkFlagRequired("cidr") - return cmd -} - -func addServiceAllowlistCidr(cidr string, description string) { - var allowlistCidrResponse api.ListServiceAllowlist - log := logging.GetConsoleLogger() - allowlistAddition := api.AllowlistCIDR{ - Cidr: cidr, - Description: description, - } - requestBodySchema := &api.ListServiceAllowlist{} - requestBodySchema.Data = append(requestBodySchema.Data, allowlistAddition) - requestBody, err := json.Marshal(requestBodySchema) - if err != nil { - log.Error().Err(err).Msg("error marshalling request body") - } - requestUrl := "/v1/serviceAllowlist/addresses/add" - client, request := factory.NewHttpRequestWithBody("POST", requestUrl, requestBody) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &allowlistCidrResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - allowlistCidrResponseJson, err := json.MarshalIndent(allowlistCidrResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal lookupTableResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(allowlistCidrResponseJson)) - } -} diff --git a/pkg/cmd/service-allowlist/disable/disable.go b/pkg/cmd/service-allowlist/disable/disable.go deleted file mode 100644 index 81bf13ff..00000000 --- a/pkg/cmd/service-allowlist/disable/disable.go +++ /dev/null @@ -1,69 +0,0 @@ -package disable - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "net/url" -) - -func NewCmdServiceAllowlistDisable() *cobra.Command { - var ( - login bool - content bool - both bool - ) - - cmd := &cobra.Command{ - Use: "disable", - Short: "Disable service allowlisting functionality for login/API authentication or content sharing for the organization.", - Run: func(cmd *cobra.Command, args []string) { - disableServiceAllowlist(login, content, both) - }, - } - cmd.Flags().BoolVar(&login, "login", false, "Set to true if you want the allowlist to affect logins") - cmd.Flags().BoolVar(&content, "content", false, "Set to true if you want the allowlist to affect content") - cmd.Flags().BoolVar(&both, "both", false, "Set to true if you want the allowlist to affect both logins and content") - return cmd -} - -func disableServiceAllowlist(login bool, content bool, both bool) { - log := logging.GetConsoleLogger() - requestUrl := "/v1/serviceAllowlist/disable" - client, request := factory.NewHttpRequest("POST", requestUrl) - query := url.Values{} - if login == true { - query.Add("allowlistType", "Login") - } else if content == true { - query.Add("allowlistType", "Content") - } else if both == true { - query.Add("allowlistType", "Both") - } else { - log.Fatal().Msg("Please set either login, content or both to true") - } - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - if response.StatusCode != 204 { - var responseError api.ResponseError - err := json.Unmarshal(responseBody, &responseError) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - } else { - fmt.Println("Service Allowlist is disabled.") - } -} diff --git a/pkg/cmd/service-allowlist/enable/enable.go b/pkg/cmd/service-allowlist/enable/enable.go deleted file mode 100644 index 1eff40a5..00000000 --- a/pkg/cmd/service-allowlist/enable/enable.go +++ /dev/null @@ -1,71 +0,0 @@ -package enable - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" - "net/url" -) - -func NewCmdServiceAllowListEnable() *cobra.Command { - var ( - login bool - content bool - both bool - ) - - cmd := &cobra.Command{ - Use: "enable", - Short: "Enable service allowlisting functionality for the organization.", - Long: "The service allowlisting can be for 1. Login: If enabled, access to Sumo Logic is granted only to CIDRs/IP addresses that are allowlisted. " + - "2. Content: If enabled, dashboards can be shared with users connecting from CIDRs/IP addresses that are allowlisted without logging in.", - Run: func(cmd *cobra.Command, args []string) { - enableServiceAllowlist(login, content, both) - }, - } - cmd.Flags().BoolVar(&login, "login", false, "Set to true if you want the allowlist to affect logins") - cmd.Flags().BoolVar(&content, "content", false, "Set to true if you want the allowlist to affect content") - cmd.Flags().BoolVar(&both, "both", false, "Set to true if you want the allowlist to affect both logins and content") - return cmd -} - -func enableServiceAllowlist(login bool, content bool, both bool) { - log := logging.GetConsoleLogger() - requestUrl := "/v1/serviceAllowlist/enable" - client, request := factory.NewHttpRequest("POST", requestUrl) - query := url.Values{} - if login == true { - query.Add("allowlistType", "Login") - } else if content == true { - query.Add("allowlistType", "Content") - } else if both == true { - query.Add("allowlistType", "Both") - } else { - log.Fatal().Msg("Please set either login, content or both to true") - } - request.URL.RawQuery = query.Encode() - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request") - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - if response.StatusCode != 204 { - var responseError api.ResponseError - err := json.Unmarshal(responseBody, &responseError) - if err != nil { - log.Error().Err(err).Msg("error unmarshalling response body") - } - } else { - fmt.Println("Service Allowlist is enabled.") - } -} diff --git a/pkg/cmd/service-allowlist/list/list.go b/pkg/cmd/service-allowlist/list/list.go deleted file mode 100644 index 1f30bfd4..00000000 --- a/pkg/cmd/service-allowlist/list/list.go +++ /dev/null @@ -1,55 +0,0 @@ -package list - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdServiceAllowlistList() *cobra.Command { - cmd := &cobra.Command{ - Use: "list", - Short: "Get a list of all allowlisted CIDR notations and/or IP addresses for the organization.", - Run: func(cmd *cobra.Command, args []string) { - listServiceAllowlist() - }, - } - return cmd -} - -func listServiceAllowlist() { - var allowlistResponse api.ListServiceAllowlist - log := logging.GetConsoleLogger() - requestUrl := "/v1/serviceAllowlist/addresses" - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &allowlistResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - allowlistResponseJson, err := json.MarshalIndent(allowlistResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal lookupTableResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(allowlistResponseJson)) - } -} diff --git a/pkg/cmd/service-allowlist/status/status.go b/pkg/cmd/service-allowlist/status/status.go deleted file mode 100644 index 7d32e541..00000000 --- a/pkg/cmd/service-allowlist/status/status.go +++ /dev/null @@ -1,55 +0,0 @@ -package status - -import ( - "encoding/json" - "fmt" - "github.com/spf13/cobra" - "github.com/wizedkyle/sumocli/api" - "github.com/wizedkyle/sumocli/pkg/cmd/factory" - "github.com/wizedkyle/sumocli/pkg/logging" - "io" -) - -func NewCmdServiceAllowlistStatus() *cobra.Command { - cmd := &cobra.Command{ - Use: "status", - Short: "Get the status of the service allowlisting functionality for login/API authentication or content sharing for the organization.", - Run: func(cmd *cobra.Command, args []string) { - getServiceAllowlistStatus() - }, - } - return cmd -} - -func getServiceAllowlistStatus() { - var allowlistStatusResponse api.GetAllowlistStatus - log := logging.GetConsoleLogger() - requestUrl := "/v1/serviceAllowlist/status" - client, request := factory.NewHttpRequest("GET", requestUrl) - response, err := client.Do(request) - if err != nil { - log.Error().Err(err).Msg("failed to make http request to " + requestUrl) - } - - defer response.Body.Close() - responseBody, err := io.ReadAll(response.Body) - if err != nil { - log.Error().Err(err).Msg("failed to read response body") - } - - err = json.Unmarshal(responseBody, &allowlistStatusResponse) - if err != nil { - log.Error().Err(err).Msg("failed to unmarshal response body") - } - - allowlistStatusResponseJson, err := json.MarshalIndent(allowlistStatusResponse, "", " ") - if err != nil { - log.Error().Err(err).Msg("failed to marshal lookupTableResponse") - } - - if response.StatusCode != 200 { - factory.HttpError(response.StatusCode, responseBody, log) - } else { - fmt.Println(string(allowlistStatusResponseJson)) - } -} diff --git a/pkg/cmd/service_allowlist/add/add.go b/pkg/cmd/service_allowlist/add/add.go new file mode 100644 index 00000000..3aab319a --- /dev/null +++ b/pkg/cmd/service_allowlist/add/add.go @@ -0,0 +1,36 @@ +package add + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdServiceAllowlistAdd(client *cip.APIClient) *cobra.Command { + var ( + ipAddresses []string + descriptions []string + ) + cmd := &cobra.Command{ + Use: "add", + Short: "Add CIDR notations and/or IP addresses to the allowlist of the organization if not already there.", + Long: "When service allowlisting functionality is enabled, CIDRs/IP addresses that are allowlisted will have access to Sumo Logic and/or content sharing.", + Run: func(cmd *cobra.Command, args []string) { + addServiceAllowlistCidr(ipAddresses, descriptions, client) + }, + } + cmd.Flags().StringSliceVar(&ipAddresses, "ipAddresses", []string{}, "Specify the IP addresses to add in CIDR format. Multiple addresses can be specified by comma separating them.") + cmd.Flags().StringSliceVar(&descriptions, "description", []string{}, "Specify the descriptions for the IP addresses. Provide a comma separated list of descriptions relating to the IP addresses.") + cmd.MarkFlagRequired("cidr") + return cmd +} + +func addServiceAllowlistCidr(ipAddresses []string, descriptions []string, client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.AddAllowlistedCidrs(cmdutils.GenerateCidrList( + ipAddresses, descriptions)) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/service_allowlist/disable/disable.go b/pkg/cmd/service_allowlist/disable/disable.go new file mode 100644 index 00000000..06264fdb --- /dev/null +++ b/pkg/cmd/service_allowlist/disable/disable.go @@ -0,0 +1,48 @@ +package disable + +import ( + "fmt" + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "os" +) + +func NewCmdServiceAllowlistDisable(client *cip.APIClient) *cobra.Command { + var ( + login bool + content bool + both bool + ) + cmd := &cobra.Command{ + Use: "disable", + Short: "Disable service allowlisting functionality for login/API authentication or content sharing for the organization.", + Run: func(cmd *cobra.Command, args []string) { + disableServiceAllowlist(login, content, both, client) + }, + } + cmd.Flags().BoolVar(&login, "login", false, "Set to true if you want the allowlist to affect logins") + cmd.Flags().BoolVar(&content, "content", false, "Set to true if you want the allowlist to affect content") + cmd.Flags().BoolVar(&both, "both", false, "Set to true if you want the allowlist to affect both logins and content") + return cmd +} + +func disableServiceAllowlist(login bool, content bool, both bool, client *cip.APIClient) { + var allowlistType string + if login == true { + allowlistType = "login" + } else if content == true { + allowlistType = "content" + } else if both == true { + allowlistType = "both" + } else if login == true && content == true && both == true { + fmt.Println("Please select either login, content, or both.") + os.Exit(1) + } + httpResponse, errorResponse := client.DisableAllowlisting(allowlistType) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(nil, httpResponse, errorResponse, "Service allowlisting was disabled successfully.") + } +} diff --git a/pkg/cmd/service_allowlist/enable/enable.go b/pkg/cmd/service_allowlist/enable/enable.go new file mode 100644 index 00000000..a1c5c8de --- /dev/null +++ b/pkg/cmd/service_allowlist/enable/enable.go @@ -0,0 +1,50 @@ +package enable + +import ( + "fmt" + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" + "os" +) + +func NewCmdServiceAllowListEnable(client *cip.APIClient) *cobra.Command { + var ( + login bool + content bool + both bool + ) + cmd := &cobra.Command{ + Use: "enable", + Short: "Enable service allowlisting functionality for the organization.", + Long: "The service allowlisting can be for 1. Login: If enabled, access to Sumo Logic is granted only to CIDRs/IP addresses that are allowlisted. " + + "2. Content: If enabled, dashboards can be shared with users connecting from CIDRs/IP addresses that are allowlisted without logging in.", + Run: func(cmd *cobra.Command, args []string) { + enableServiceAllowlist(login, content, both, client) + }, + } + cmd.Flags().BoolVar(&login, "login", false, "Set to true if you want the allowlist to affect logins") + cmd.Flags().BoolVar(&content, "content", false, "Set to true if you want the allowlist to affect content") + cmd.Flags().BoolVar(&both, "both", false, "Set to true if you want the allowlist to affect both logins and content") + return cmd +} + +func enableServiceAllowlist(login bool, content bool, both bool, client *cip.APIClient) { + var allowlistType string + if login == true { + allowlistType = "login" + } else if content == true { + allowlistType = "content" + } else if both == true { + allowlistType = "both" + } else if login == true && content == true && both == true { + fmt.Println("Please select either login, content, or both.") + os.Exit(1) + } + httpResponse, errorResponse := client.EnableAllowlisting(allowlistType) + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(nil, httpResponse, errorResponse, "Service allowlisting was enabled successfully.") + } +} diff --git a/pkg/cmd/service_allowlist/list/list.go b/pkg/cmd/service_allowlist/list/list.go new file mode 100644 index 00000000..e3527ab8 --- /dev/null +++ b/pkg/cmd/service_allowlist/list/list.go @@ -0,0 +1,27 @@ +package list + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdServiceAllowlistList(client *cip.APIClient) *cobra.Command { + cmd := &cobra.Command{ + Use: "list", + Short: "Get a list of all allowlisted CIDR notations and/or IP addresses for the organization.", + Run: func(cmd *cobra.Command, args []string) { + listServiceAllowlist(client) + }, + } + return cmd +} + +func listServiceAllowlist(client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.ListAllowlistedCidrs() + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/service-allowlist/remove/remove.go b/pkg/cmd/service_allowlist/remove/remove.go similarity index 100% rename from pkg/cmd/service-allowlist/remove/remove.go rename to pkg/cmd/service_allowlist/remove/remove.go diff --git a/pkg/cmd/service-allowlist/service-allowlist.go b/pkg/cmd/service_allowlist/service_allowlist.go similarity index 75% rename from pkg/cmd/service-allowlist/service-allowlist.go rename to pkg/cmd/service_allowlist/service_allowlist.go index 0c1a27e3..6b3dd36e 100644 --- a/pkg/cmd/service-allowlist/service-allowlist.go +++ b/pkg/cmd/service_allowlist/service_allowlist.go @@ -2,25 +2,26 @@ package service_allowlist import ( "github.com/spf13/cobra" - cmdServiceAllowlistAdd "github.com/wizedkyle/sumocli/pkg/cmd/service-allowlist/add" - cmdServiceAllowlistDisable "github.com/wizedkyle/sumocli/pkg/cmd/service-allowlist/disable" - cmdServiceAllowlistEnable "github.com/wizedkyle/sumocli/pkg/cmd/service-allowlist/enable" - cmdServiceAllowlistList "github.com/wizedkyle/sumocli/pkg/cmd/service-allowlist/list" - cmdServiceAllowlistRemove "github.com/wizedkyle/sumocli/pkg/cmd/service-allowlist/remove" - cmdServiceAllowlistStatus "github.com/wizedkyle/sumocli/pkg/cmd/service-allowlist/status" + cmdServiceAllowlistAdd "github.com/wizedkyle/sumocli/pkg/cmd/service_allowlist/add" + cmdServiceAllowlistDisable "github.com/wizedkyle/sumocli/pkg/cmd/service_allowlist/disable" + cmdServiceAllowlistEnable "github.com/wizedkyle/sumocli/pkg/cmd/service_allowlist/enable" + cmdServiceAllowlistList "github.com/wizedkyle/sumocli/pkg/cmd/service_allowlist/list" + cmdServiceAllowlistRemove "github.com/wizedkyle/sumocli/pkg/cmd/service_allowlist/remove" + cmdServiceAllowlistStatus "github.com/wizedkyle/sumocli/pkg/cmd/service_allowlist/status" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdServiceAllowlist() *cobra.Command { +func NewCmdServiceAllowlist(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "service-allowlist", Short: "Manage the service allowlist", Long: "Commands that all you to manage the Service Allowlist in your Sumo Logic tenant", } - cmd.AddCommand(cmdServiceAllowlistAdd.NewCmdServiceAllowlistAdd()) - cmd.AddCommand(cmdServiceAllowlistDisable.NewCmdServiceAllowlistDisable()) - cmd.AddCommand(cmdServiceAllowlistEnable.NewCmdServiceAllowListEnable()) - cmd.AddCommand(cmdServiceAllowlistList.NewCmdServiceAllowlistList()) + cmd.AddCommand(cmdServiceAllowlistAdd.NewCmdServiceAllowlistAdd(client)) + cmd.AddCommand(cmdServiceAllowlistDisable.NewCmdServiceAllowlistDisable(client)) + cmd.AddCommand(cmdServiceAllowlistEnable.NewCmdServiceAllowListEnable(client)) + cmd.AddCommand(cmdServiceAllowlistList.NewCmdServiceAllowlistList(client)) cmd.AddCommand(cmdServiceAllowlistRemove.NewCmdServiceAllowlistRemove()) - cmd.AddCommand(cmdServiceAllowlistStatus.NewCmdServiceAllowlistStatus()) + cmd.AddCommand(cmdServiceAllowlistStatus.NewCmdServiceAllowlistStatus(client)) return cmd } diff --git a/pkg/cmd/service_allowlist/status/status.go b/pkg/cmd/service_allowlist/status/status.go new file mode 100644 index 00000000..a85afa1a --- /dev/null +++ b/pkg/cmd/service_allowlist/status/status.go @@ -0,0 +1,27 @@ +package status + +import ( + "github.com/spf13/cobra" + "github.com/wizedkyle/sumocli/pkg/cmdutils" + "github.com/wizedkyle/sumologic-go-sdk/service/cip" +) + +func NewCmdServiceAllowlistStatus(client *cip.APIClient) *cobra.Command { + cmd := &cobra.Command{ + Use: "status", + Short: "Get the status of the service allowlisting functionality for login/API authentication or content sharing for the organization.", + Run: func(cmd *cobra.Command, args []string) { + getServiceAllowlistStatus(client) + }, + } + return cmd +} + +func getServiceAllowlistStatus(client *cip.APIClient) { + apiResponse, httpResponse, errorResponse := client.GetAllowlistingStatus() + if errorResponse != nil { + cmdutils.OutputError(httpResponse, errorResponse) + } else { + cmdutils.Output(apiResponse, httpResponse, errorResponse, "") + } +} diff --git a/pkg/cmd/sources/azure_event_hub/azure_event_hub.go b/pkg/cmd/sources/azure_event_hub/azure_event_hub.go index bec47c4e..b32ee65a 100644 --- a/pkg/cmd/sources/azure_event_hub/azure_event_hub.go +++ b/pkg/cmd/sources/azure_event_hub/azure_event_hub.go @@ -1,7 +1,6 @@ package azure_event_hub import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" NewCmdAzureEventHubCreate "github.com/wizedkyle/sumocli/pkg/cmd/sources/azure_event_hub/create" NewCmdAzureEventHubGet "github.com/wizedkyle/sumocli/pkg/cmd/sources/azure_event_hub/get" @@ -9,15 +8,15 @@ import ( "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdAzureEventHubSource(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAzureEventHubSource(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "azure-event-hub", Short: "The Azure Event Hubs Source provides a secure endpoint to receive data from Azure Event Hubs. " + "It securely stores the required authentication, scheduling, and state tracking information. " + "This source is used to collect activity and resource logs from Azure.", } - cmd.AddCommand(NewCmdAzureEventHubCreate.NewCmdAzureEventHubSourceCreate(client, log)) - cmd.AddCommand(NewCmdAzureEventHubGet.NewCmdAzureEventHubSourceGet(client, log)) - cmd.AddCommand(NewCmdAzureEventHubUpdate.NewCmdAzureEventHubSourceUpdate(client, log)) + cmd.AddCommand(NewCmdAzureEventHubCreate.NewCmdAzureEventHubSourceCreate(client)) + cmd.AddCommand(NewCmdAzureEventHubGet.NewCmdAzureEventHubSourceGet(client)) + cmd.AddCommand(NewCmdAzureEventHubUpdate.NewCmdAzureEventHubSourceUpdate(client)) return cmd } diff --git a/pkg/cmd/sources/azure_event_hub/create/create.go b/pkg/cmd/sources/azure_event_hub/create/create.go index 1fb96e5d..89cdb3c3 100644 --- a/pkg/cmd/sources/azure_event_hub/create/create.go +++ b/pkg/cmd/sources/azure_event_hub/create/create.go @@ -1,14 +1,13 @@ package create import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdAzureEventHubSourceCreate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAzureEventHubSourceCreate(client *cip.APIClient) *cobra.Command { var ( authorizationRuleName string category string @@ -27,7 +26,7 @@ func NewCmdAzureEventHubSourceCreate(client *cip.APIClient, log *zerolog.Logger) Short: "Creates an Azure Event Hub source", Run: func(cmd *cobra.Command, args []string) { createEventHubSource(authorizationRuleName, category, collectorId, consumerGroup, description, eventHubKey, - eventHubName, fieldNames, fieldValues, name, namespace, client, log) + eventHubName, fieldNames, fieldValues, name, namespace, client) }, } cmd.Flags().StringVar(&authorizationRuleName, "authorizationRuleName", "", "Specify the name of the Event Hub Authorization Rule") @@ -55,7 +54,7 @@ func NewCmdAzureEventHubSourceCreate(client *cip.APIClient, log *zerolog.Logger) func createEventHubSource(authorizationRuleName string, category string, collectorId string, consumerGroup string, description string, eventHubKey string, eventHubName string, fieldNames []string, fieldValues []string, name string, namespace string, - client *cip.APIClient, log *zerolog.Logger) { + client *cip.APIClient) { fields := cmdutils.GenerateFieldsMap(fieldNames, fieldValues) body := types.CreateEventHubSourceRequest{ ApiVersion: "v1", @@ -80,7 +79,7 @@ func createEventHubSource(authorizationRuleName string, category string, collect } apiResponse, httpResponse, errorResponse := client.CreateEventHubSource(body, collectorId) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to create azure event hub source") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/sources/azure_event_hub/get/get.go b/pkg/cmd/sources/azure_event_hub/get/get.go index b0d25fde..6005dfb3 100644 --- a/pkg/cmd/sources/azure_event_hub/get/get.go +++ b/pkg/cmd/sources/azure_event_hub/get/get.go @@ -1,13 +1,12 @@ package get import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdAzureEventHubSourceGet(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAzureEventHubSourceGet(client *cip.APIClient) *cobra.Command { var ( collectorId string sourceId string @@ -16,7 +15,7 @@ func NewCmdAzureEventHubSourceGet(client *cip.APIClient, log *zerolog.Logger) *c Use: "get", Short: "Gets information about an Azure Event Hub source", Run: func(cmd *cobra.Command, args []string) { - getEventHubSource(collectorId, sourceId, client, log) + getEventHubSource(collectorId, sourceId, client) }, } cmd.Flags().StringVar(&collectorId, "collectorId", "", "Specify the collector id that the source is associated to") @@ -24,10 +23,10 @@ func NewCmdAzureEventHubSourceGet(client *cip.APIClient, log *zerolog.Logger) *c return cmd } -func getEventHubSource(collectorId string, sourceId string, client *cip.APIClient, log *zerolog.Logger) { +func getEventHubSource(collectorId string, sourceId string, client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.GetEventHubSource(collectorId, sourceId) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to get event hub source") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/sources/azure_event_hub/update/update.go b/pkg/cmd/sources/azure_event_hub/update/update.go index b3685988..6dc56044 100644 --- a/pkg/cmd/sources/azure_event_hub/update/update.go +++ b/pkg/cmd/sources/azure_event_hub/update/update.go @@ -1,7 +1,7 @@ package update import ( - "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" @@ -9,7 +9,7 @@ import ( "strconv" ) -func NewCmdAzureEventHubSourceUpdate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdAzureEventHubSourceUpdate(client *cip.APIClient) *cobra.Command { var ( authorizationRuleName string category string @@ -29,7 +29,7 @@ func NewCmdAzureEventHubSourceUpdate(client *cip.APIClient, log *zerolog.Logger) Short: "Updates an Azure Event Hub source", Run: func(cmd *cobra.Command, args []string) { updateEventHubSource(authorizationRuleName, category, collectorId, consumerGroup, description, eventHubKey, - eventHubName, fieldNames, fieldValues, name, namespace, sourceId, client, log) + eventHubName, fieldNames, fieldValues, name, namespace, sourceId, client) }, } cmd.Flags().StringVar(&authorizationRuleName, "authorizationRuleName", "", "Specify the name of the Event Hub Authorization Rule") @@ -59,7 +59,7 @@ func NewCmdAzureEventHubSourceUpdate(client *cip.APIClient, log *zerolog.Logger) func updateEventHubSource(authorizationRuleName string, category string, collectorId string, consumerGroup string, description string, eventHubKey string, eventHubName string, fieldNames []string, fieldValues []string, name string, namespace string, sourceId string, - client *cip.APIClient, log *zerolog.Logger) { + client *cip.APIClient) { sourceIdInt, err := strconv.Atoi(sourceId) if err != nil { log.Error().Err(err).Msg("failed to convert string to int") @@ -88,7 +88,7 @@ func updateEventHubSource(authorizationRuleName string, category string, collect } apiResponse, httpResponse, errorResponse := client.UpdateEventHubSource(body, collectorId, sourceId) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to update event hub source") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/sources/sources.go b/pkg/cmd/sources/sources.go index 9dfc1468..3f7d99ea 100644 --- a/pkg/cmd/sources/sources.go +++ b/pkg/cmd/sources/sources.go @@ -1,7 +1,6 @@ package sources import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" cmdAwsCloudTrailSource "github.com/wizedkyle/sumocli/pkg/cmd/sources/aws_cloudtrail" cmdAWSS3ArchiveSource "github.com/wizedkyle/sumocli/pkg/cmd/sources/aws_s3_archive" @@ -13,14 +12,14 @@ import ( "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdSources(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdSources(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "sources", Short: "Manages sources assigned to collectors", } cmd.AddCommand(cmdAwsCloudTrailSource.NewCmdAWSCloudTrailSource()) cmd.AddCommand(cmdAWSS3ArchiveSource.NewCmdAWSS3ArchiveSource()) - cmd.AddCommand(cmdAzureEventHubSource.NewCmdAzureEventHubSource(client, log)) + cmd.AddCommand(cmdAzureEventHubSource.NewCmdAzureEventHubSource(client)) cmd.AddCommand(cmdSourcesDelete.NewCmdDeleteSource()) cmd.AddCommand(cmdHttpSources.NewCmdHttpSources()) cmd.AddCommand(cmdSourcesList.NewCmdSourceList()) diff --git a/pkg/cmd/tokens/create/create.go b/pkg/cmd/tokens/create/create.go index 98bd5b63..258c62f7 100644 --- a/pkg/cmd/tokens/create/create.go +++ b/pkg/cmd/tokens/create/create.go @@ -1,14 +1,13 @@ package create import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdTokensCreate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdTokensCreate(client *cip.APIClient) *cobra.Command { var ( description string inactive bool @@ -18,7 +17,7 @@ func NewCmdTokensCreate(client *cip.APIClient, log *zerolog.Logger) *cobra.Comma Use: "create", Short: "Create a token in the token library.", Run: func(cmd *cobra.Command, args []string) { - createToken(description, inactive, name, client, log) + createToken(description, inactive, name, client) }, } cmd.Flags().StringVar(&description, "description", "", "Specify a description for the token") @@ -28,7 +27,7 @@ func NewCmdTokensCreate(client *cip.APIClient, log *zerolog.Logger) *cobra.Comma return cmd } -func createToken(description string, inactive bool, name string, client *cip.APIClient, log *zerolog.Logger) { +func createToken(description string, inactive bool, name string, client *cip.APIClient) { var options types.TokenBaseDefinition if inactive == true { options.Status = "Inactive" @@ -40,7 +39,7 @@ func createToken(description string, inactive bool, name string, client *cip.API options.Type_ = "CollectorRegistration" apiResponse, httpResponse, errorResponse := client.CreateToken(options) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to create token") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/tokens/delete/delete.go b/pkg/cmd/tokens/delete/delete.go index 15156d4f..c6946657 100644 --- a/pkg/cmd/tokens/delete/delete.go +++ b/pkg/cmd/tokens/delete/delete.go @@ -1,19 +1,18 @@ package delete import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdTokensDelete(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdTokensDelete(client *cip.APIClient) *cobra.Command { var id string cmd := &cobra.Command{ Use: "delete", Short: "Delete a token with the given identifier in the token library.", Run: func(cmd *cobra.Command, args []string) { - deleteToken(id, client, log) + deleteToken(id, client) }, } cmd.Flags().StringVar(&id, "id", "", "Specify id of the token to delete") @@ -21,10 +20,10 @@ func NewCmdTokensDelete(client *cip.APIClient, log *zerolog.Logger) *cobra.Comma return cmd } -func deleteToken(id string, client *cip.APIClient, log *zerolog.Logger) { +func deleteToken(id string, client *cip.APIClient) { httpResponse, errorResponse := client.DeleteToken(id) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to delete token") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(nil, httpResponse, errorResponse, "Token was deleted.") } diff --git a/pkg/cmd/tokens/get/get.go b/pkg/cmd/tokens/get/get.go index 16afe818..4077d914 100644 --- a/pkg/cmd/tokens/get/get.go +++ b/pkg/cmd/tokens/get/get.go @@ -1,19 +1,18 @@ package get import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdTokensGet(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdTokensGet(client *cip.APIClient) *cobra.Command { var id string cmd := &cobra.Command{ Use: "get", Short: "Get a token with the given identifier in the token library.", Run: func(cmd *cobra.Command, args []string) { - getToken(id, client, log) + getToken(id, client) }, } cmd.Flags().StringVar(&id, "id", "", "Specify the id of the token to retrieve") @@ -21,10 +20,10 @@ func NewCmdTokensGet(client *cip.APIClient, log *zerolog.Logger) *cobra.Command return cmd } -func getToken(id string, client *cip.APIClient, log *zerolog.Logger) { +func getToken(id string, client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.GetToken(id) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to get token") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/tokens/list/list.go b/pkg/cmd/tokens/list/list.go index 0df41145..7314f1a0 100644 --- a/pkg/cmd/tokens/list/list.go +++ b/pkg/cmd/tokens/list/list.go @@ -1,27 +1,26 @@ package list import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdTokensList(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdTokensList(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "list", Short: "Get a list of all tokens in the token library.", Run: func(cmd *cobra.Command, args []string) { - listTokens(client, log) + listTokens(client) }, } return cmd } -func listTokens(client *cip.APIClient, log *zerolog.Logger) { +func listTokens(client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.ListTokens() if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to list tokens") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/tokens/tokens.go b/pkg/cmd/tokens/tokens.go index cd1efa7b..23d876e0 100644 --- a/pkg/cmd/tokens/tokens.go +++ b/pkg/cmd/tokens/tokens.go @@ -1,7 +1,6 @@ package tokens import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" cmdTokensCreate "github.com/wizedkyle/sumocli/pkg/cmd/tokens/create" cmdTokensDelete "github.com/wizedkyle/sumocli/pkg/cmd/tokens/delete" @@ -11,16 +10,16 @@ import ( "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdTokens(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdTokens(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "tokens", Short: "Manage tokens", Long: "Commands that allow you to manage Tokens in your Sumo Logic tenant", } - cmd.AddCommand(cmdTokensCreate.NewCmdTokensCreate(client, log)) - cmd.AddCommand(cmdTokensDelete.NewCmdTokensDelete(client, log)) - cmd.AddCommand(cmdTokensGet.NewCmdTokensGet(client, log)) - cmd.AddCommand(cmdTokensList.NewCmdTokensList(client, log)) - cmd.AddCommand(cmdTokensUpdate.NewCmdTokensUpdate(client, log)) + cmd.AddCommand(cmdTokensCreate.NewCmdTokensCreate(client)) + cmd.AddCommand(cmdTokensDelete.NewCmdTokensDelete(client)) + cmd.AddCommand(cmdTokensGet.NewCmdTokensGet(client)) + cmd.AddCommand(cmdTokensList.NewCmdTokensList(client)) + cmd.AddCommand(cmdTokensUpdate.NewCmdTokensUpdate(client)) return cmd } diff --git a/pkg/cmd/tokens/update/update.go b/pkg/cmd/tokens/update/update.go index 5e7b3424..93b94697 100644 --- a/pkg/cmd/tokens/update/update.go +++ b/pkg/cmd/tokens/update/update.go @@ -1,14 +1,13 @@ package update import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdTokensUpdate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdTokensUpdate(client *cip.APIClient) *cobra.Command { var ( description string id string @@ -20,7 +19,7 @@ func NewCmdTokensUpdate(client *cip.APIClient, log *zerolog.Logger) *cobra.Comma Use: "update", Short: "Update a token with the given identifier in the token library.", Run: func(cmd *cobra.Command, args []string) { - updateToken(description, id, inactive, name, version, client, log) + updateToken(description, id, inactive, name, version, client) }, } cmd.Flags().StringVar(&description, "description", "", "Specify a description for the token") @@ -34,7 +33,7 @@ func NewCmdTokensUpdate(client *cip.APIClient, log *zerolog.Logger) *cobra.Comma return cmd } -func updateToken(description string, id string, inactive bool, name string, version int64, client *cip.APIClient, log *zerolog.Logger) { +func updateToken(description string, id string, inactive bool, name string, version int64, client *cip.APIClient) { var options types.TokenBaseDefinitionUpdate if inactive == true { options.Status = "Inactive" @@ -47,7 +46,7 @@ func updateToken(description string, id string, inactive bool, name string, vers options.Version = version apiResponse, httpResponse, errorResponse := client.UpdateToken(options, id) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to update token") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/users/change_email/change_email.go b/pkg/cmd/users/change_email/change_email.go index 71cd62cb..de286d62 100644 --- a/pkg/cmd/users/change_email/change_email.go +++ b/pkg/cmd/users/change_email/change_email.go @@ -1,14 +1,13 @@ package change_email import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdUserChangeEmail(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdUserChangeEmail(client *cip.APIClient) *cobra.Command { var ( id string email string @@ -17,7 +16,7 @@ func NewCmdUserChangeEmail(client *cip.APIClient, log *zerolog.Logger) *cobra.Co Use: "change-email", Short: "Changes the email address of a Sumo Logic user.", Run: func(cmd *cobra.Command, args []string) { - userChangeEmail(id, email, client, log) + userChangeEmail(id, email, client) }, } cmd.Flags().StringVar(&id, "id", "", "Specify the id of the user that needs to have the email changed.") @@ -27,13 +26,13 @@ func NewCmdUserChangeEmail(client *cip.APIClient, log *zerolog.Logger) *cobra.Co return cmd } -func userChangeEmail(id string, email string, client *cip.APIClient, log *zerolog.Logger) { +func userChangeEmail(id string, email string, client *cip.APIClient) { httpResponse, errorResponse := client.RequestChangeEmail(types.ChangeEmailRequest{ Email: email, }, id) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to change user email") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(nil, httpResponse, errorResponse, "Email change request was submitted successfully.") } diff --git a/pkg/cmd/users/create/create.go b/pkg/cmd/users/create/create.go index 5253c076..5933238c 100644 --- a/pkg/cmd/users/create/create.go +++ b/pkg/cmd/users/create/create.go @@ -1,14 +1,13 @@ package create import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdUserCreate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdUserCreate(client *cip.APIClient) *cobra.Command { var ( firstName string lastName string @@ -19,7 +18,7 @@ func NewCmdUserCreate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command Use: "create", Short: "Creates a Sumo Logic user account", Run: func(cmd *cobra.Command, args []string) { - user(firstName, lastName, emailAddress, roleIds, client, log) + user(firstName, lastName, emailAddress, roleIds, client) }, } cmd.Flags().StringVar(&firstName, "firstName", "", "First name of the user") @@ -33,7 +32,7 @@ func NewCmdUserCreate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command return cmd } -func user(firstName string, lastName string, emailAddress string, roleIds []string, client *cip.APIClient, log *zerolog.Logger) { +func user(firstName string, lastName string, emailAddress string, roleIds []string, client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.CreateUser(types.CreateUserDefinition{ FirstName: firstName, LastName: lastName, @@ -41,7 +40,7 @@ func user(firstName string, lastName string, emailAddress string, roleIds []stri RoleIds: roleIds, }) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to create user") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/users/delete/delete.go b/pkg/cmd/users/delete/delete.go index c8bd49a0..b9592468 100644 --- a/pkg/cmd/users/delete/delete.go +++ b/pkg/cmd/users/delete/delete.go @@ -2,14 +2,13 @@ package delete import ( "github.com/antihax/optional" - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdUserDelete(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdUserDelete(client *cip.APIClient) *cobra.Command { var ( id string transferTo string @@ -18,7 +17,7 @@ func NewCmdUserDelete(client *cip.APIClient, log *zerolog.Logger) *cobra.Command Use: "delete", Short: "Deletes a Sumo Logic user", Run: func(cmd *cobra.Command, args []string) { - deleteUser(id, transferTo, client, log) + deleteUser(id, transferTo, client) }, } cmd.Flags().StringVar(&id, "id", "", "Specify the id of the user to delete") @@ -27,14 +26,14 @@ func NewCmdUserDelete(client *cip.APIClient, log *zerolog.Logger) *cobra.Command return cmd } -func deleteUser(id string, transferTo string, client *cip.APIClient, log *zerolog.Logger) { - var options types.UserManagementApiDeleteUserOpts +func deleteUser(id string, transferTo string, client *cip.APIClient) { + var options types.DeleteUserOpts if transferTo != "" { options.TransferTo = optional.NewString(transferTo) } httpResponse, errorResponse := client.DeleteUser(id, &options) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to delete user") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(nil, httpResponse, errorResponse, "User was deleted successfully.") } diff --git a/pkg/cmd/users/disable_mfa/disable_mfa.go b/pkg/cmd/users/disable_mfa/disable_mfa.go index 2737f85a..fbfe4e22 100644 --- a/pkg/cmd/users/disable_mfa/disable_mfa.go +++ b/pkg/cmd/users/disable_mfa/disable_mfa.go @@ -3,25 +3,25 @@ package disable_mfa import ( "errors" "github.com/manifoldco/promptui" - "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdUserDisableMFA(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdUserDisableMFA(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "disable-mfa", Short: "Disables MFA for a Sumo Logic user (this command only works interactively).", Run: func(cmd *cobra.Command, args []string) { - userDisableMFA(client, log) + userDisableMFA(client) }, } return cmd } -func userDisableMFA(client *cip.APIClient, log *zerolog.Logger) { +func userDisableMFA(client *cip.APIClient) { validate := func(input string) error { if input == "" { return errors.New("Value is empty") @@ -58,7 +58,7 @@ func userDisableMFA(client *cip.APIClient, log *zerolog.Logger) { }, idResult) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to disable mfa") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(nil, httpResponse, errorResponse, "User's MFA was disabled successfully.") } diff --git a/pkg/cmd/users/get/get.go b/pkg/cmd/users/get/get.go index 1213fa7f..166001e0 100644 --- a/pkg/cmd/users/get/get.go +++ b/pkg/cmd/users/get/get.go @@ -1,19 +1,18 @@ package get import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdGetUser(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdGetUser(client *cip.APIClient) *cobra.Command { var id string cmd := &cobra.Command{ Use: "get", Short: "Gets a Sumo Logic user", Run: func(cmd *cobra.Command, args []string) { - getUser(id, client, log) + getUser(id, client) }, } cmd.Flags().StringVar(&id, "id", "", "Specify the id of the user to get") @@ -21,10 +20,10 @@ func NewCmdGetUser(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { return cmd } -func getUser(id string, client *cip.APIClient, log *zerolog.Logger) { +func getUser(id string, client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.GetUser(id) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to get user") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/users/list/list.go b/pkg/cmd/users/list/list.go index 86654f9b..395de2ac 100644 --- a/pkg/cmd/users/list/list.go +++ b/pkg/cmd/users/list/list.go @@ -2,14 +2,13 @@ package list import ( "github.com/antihax/optional" - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdUserList(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdUserList(client *cip.APIClient) *cobra.Command { var ( email string limit int32 @@ -19,7 +18,7 @@ func NewCmdUserList(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { Use: "list", Short: "Lists Sumo Logic users", Run: func(cmd *cobra.Command, args []string) { - listUsers(email, limit, sortBy, client, log) + listUsers(email, limit, sortBy, client) }, } cmd.Flags().StringVar(&email, "email", "", "Specify the email address of the user") @@ -28,8 +27,8 @@ func NewCmdUserList(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { return cmd } -func listUsers(email string, limit int32, sortBy string, client *cip.APIClient, log *zerolog.Logger) { - var options types.UserManagementApiListUsersOpts +func listUsers(email string, limit int32, sortBy string, client *cip.APIClient) { + var options types.ListUsersOpts var paginationToken string options.Limit = optional.NewInt32(limit) if email != "" { @@ -40,22 +39,22 @@ func listUsers(email string, limit int32, sortBy string, client *cip.APIClient, } apiResponse, httpResponse, errorResponse := client.ListUsers(&options) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to list users") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } paginationToken = apiResponse.Next for paginationToken != "" { - apiResponse = listUsersPagination(client, options, paginationToken, log) + apiResponse = listUsersPagination(client, options, paginationToken) paginationToken = apiResponse.Next } } -func listUsersPagination(client *cip.APIClient, options types.UserManagementApiListUsersOpts, token string, log *zerolog.Logger) types.ListUserModelsResponse { +func listUsersPagination(client *cip.APIClient, options types.ListUsersOpts, token string) types.ListUserModelsResponse { options.Token = optional.NewString(token) apiResponse, httpResponse, errorResponse := client.ListUsers(&options) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to list users") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/users/reset_password/reset_password.go b/pkg/cmd/users/reset_password/reset_password.go index 0fae1233..fbc5a818 100644 --- a/pkg/cmd/users/reset_password/reset_password.go +++ b/pkg/cmd/users/reset_password/reset_password.go @@ -1,19 +1,18 @@ package reset_password import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdUserResetPassword(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdUserResetPassword(client *cip.APIClient) *cobra.Command { var id string cmd := &cobra.Command{ Use: "reset-password", Short: "Initiates a password reset for a Sumo Logic user.", Run: func(cmd *cobra.Command, args []string) { - userResetPassword(id, client, log) + userResetPassword(id, client) }, } cmd.Flags().StringVar(&id, "id", "", "Specify the id of the user which requires a password reset.") @@ -21,10 +20,10 @@ func NewCmdUserResetPassword(client *cip.APIClient, log *zerolog.Logger) *cobra. return cmd } -func userResetPassword(id string, client *cip.APIClient, log *zerolog.Logger) { +func userResetPassword(id string, client *cip.APIClient) { httpResponse, errorResponse := client.ResetPassword(id) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to reset password") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(nil, httpResponse, errorResponse, "User's password was reset successfully.") } diff --git a/pkg/cmd/users/unlock/unlock.go b/pkg/cmd/users/unlock/unlock.go index 7bd48bb6..eb8c4351 100644 --- a/pkg/cmd/users/unlock/unlock.go +++ b/pkg/cmd/users/unlock/unlock.go @@ -1,19 +1,18 @@ package unlock import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdUnlockUser(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdUnlockUser(client *cip.APIClient) *cobra.Command { var id string cmd := &cobra.Command{ Use: "unlock", Short: "Unlocks a Sumo Logic user account", Run: func(cmd *cobra.Command, args []string) { - unlockUser(id, client, log) + unlockUser(id, client) }, } cmd.Flags().StringVar(&id, "id", "", "Specify the id of the user account to unlock") @@ -21,10 +20,10 @@ func NewCmdUnlockUser(client *cip.APIClient, log *zerolog.Logger) *cobra.Command return cmd } -func unlockUser(id string, client *cip.APIClient, log *zerolog.Logger) { +func unlockUser(id string, client *cip.APIClient) { httpResponse, errorResponse := client.UnlockUser(id) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to unlock user") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(nil, httpResponse, errorResponse, "User's account was unlocked successfully.") } diff --git a/pkg/cmd/users/update/update.go b/pkg/cmd/users/update/update.go index 0802a782..319a323c 100644 --- a/pkg/cmd/users/update/update.go +++ b/pkg/cmd/users/update/update.go @@ -1,14 +1,13 @@ package update import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/wizedkyle/sumocli/pkg/cmdutils" "github.com/wizedkyle/sumologic-go-sdk/service/cip" "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" ) -func NewCmdUserUpdate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdUserUpdate(client *cip.APIClient) *cobra.Command { var ( id string firstName string @@ -20,7 +19,7 @@ func NewCmdUserUpdate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command Use: "update", Short: "Updates a Sumo Logic user.", Run: func(cmd *cobra.Command, args []string) { - updateUser(id, firstName, lastName, isActive, roleIds, client, log) + updateUser(id, firstName, lastName, isActive, roleIds, client) }, } cmd.Flags().StringVar(&id, "id", "", "Specify the id of the user to update.") @@ -36,7 +35,7 @@ func NewCmdUserUpdate(client *cip.APIClient, log *zerolog.Logger) *cobra.Command return cmd } -func updateUser(id string, firstName string, lastName string, isActive bool, roleIds []string, client *cip.APIClient, log *zerolog.Logger) { +func updateUser(id string, firstName string, lastName string, isActive bool, roleIds []string, client *cip.APIClient) { apiResponse, httpResponse, errorResponse := client.UpdateUser(types.UpdateUserDefinition{ FirstName: firstName, LastName: lastName, @@ -45,7 +44,7 @@ func updateUser(id string, firstName string, lastName string, isActive bool, rol }, id) if errorResponse != nil { - log.Error().Err(errorResponse).Msg("failed to update user") + cmdutils.OutputError(httpResponse, errorResponse) } else { cmdutils.Output(apiResponse, httpResponse, errorResponse, "") } diff --git a/pkg/cmd/users/users.go b/pkg/cmd/users/users.go index e6549117..4f7cb930 100644 --- a/pkg/cmd/users/users.go +++ b/pkg/cmd/users/users.go @@ -1,7 +1,6 @@ package users import ( - "github.com/rs/zerolog" "github.com/spf13/cobra" cmdUserChange "github.com/wizedkyle/sumocli/pkg/cmd/users/change_email" cmdUserCreate "github.com/wizedkyle/sumocli/pkg/cmd/users/create" @@ -15,21 +14,21 @@ import ( "github.com/wizedkyle/sumologic-go-sdk/service/cip" ) -func NewCmdUser(client *cip.APIClient, log *zerolog.Logger) *cobra.Command { +func NewCmdUser(client *cip.APIClient) *cobra.Command { cmd := &cobra.Command{ Use: "users ", Short: "Manage users", Long: "Work with Sumo Logic users", } - cmd.AddCommand(cmdUserChange.NewCmdUserChangeEmail(client, log)) - cmd.AddCommand(cmdUserCreate.NewCmdUserCreate(client, log)) - cmd.AddCommand(cmdUserDelete.NewCmdUserDelete(client, log)) - cmd.AddCommand(cmdUserDisable.NewCmdUserDisableMFA(client, log)) - cmd.AddCommand(cmdUserGet.NewCmdGetUser(client, log)) - cmd.AddCommand(cmdUserList.NewCmdUserList(client, log)) - cmd.AddCommand(cmduserReset.NewCmdUserResetPassword(client, log)) - cmd.AddCommand(cmdUserUnlock.NewCmdUnlockUser(client, log)) - cmd.AddCommand(cmdUserUpdate.NewCmdUserUpdate(client, log)) + cmd.AddCommand(cmdUserChange.NewCmdUserChangeEmail(client)) + cmd.AddCommand(cmdUserCreate.NewCmdUserCreate(client)) + cmd.AddCommand(cmdUserDelete.NewCmdUserDelete(client)) + cmd.AddCommand(cmdUserDisable.NewCmdUserDisableMFA(client)) + cmd.AddCommand(cmdUserGet.NewCmdGetUser(client)) + cmd.AddCommand(cmdUserList.NewCmdUserList(client)) + cmd.AddCommand(cmduserReset.NewCmdUserResetPassword(client)) + cmd.AddCommand(cmdUserUnlock.NewCmdUnlockUser(client)) + cmd.AddCommand(cmdUserUpdate.NewCmdUserUpdate(client)) return cmd } diff --git a/pkg/cmdutils/errors.go b/pkg/cmdutils/errors.go index f5cc8bc9..b4fda1ed 100644 --- a/pkg/cmdutils/errors.go +++ b/pkg/cmdutils/errors.go @@ -1 +1,28 @@ package cmdutils + +import ( + "fmt" + "net/http" +) + +func OutputError(httpResponse *http.Response, err error) { + if httpResponse.StatusCode == 400 { + fmt.Println(err) + } else if httpResponse.StatusCode == 401 { + fmt.Println("Unauthorized access please check the user exists, and credentials are valid.") + } else if httpResponse.StatusCode == 403 { + fmt.Println("This operation is not allowed for your account type or the user doesn't have the role capability to perform this action.") + } else if httpResponse.StatusCode == 404 { + fmt.Println("Requested resource could not be found.") + } else if httpResponse.StatusCode == 405 { + fmt.Println("Unsupported method for URL.") + } else if httpResponse.StatusCode == 415 { + fmt.Println("Invalid content type.") + } else if httpResponse.StatusCode == 429 { + fmt.Println("The API request rate is higher than 4 request per second or inflight API requests are higher than 10 requests per second.") + } else if httpResponse.StatusCode == 500 { + fmt.Println("Internal server error.") + } else if httpResponse.StatusCode == 503 { + fmt.Println("Service is currently unavailable.") + } +} diff --git a/pkg/cmdutils/fields.go b/pkg/cmdutils/fields.go index d9b52b54..ebc177e4 100644 --- a/pkg/cmdutils/fields.go +++ b/pkg/cmdutils/fields.go @@ -1,5 +1,7 @@ package cmdutils +import "github.com/wizedkyle/sumologic-go-sdk/service/cip/types" + func GenerateFieldsMap(fieldNames []string, fieldValues []string) map[string]string { if len(fieldNames) > 0 && len(fieldValues) > 0 { fieldsMap := make(map[string]string) @@ -12,3 +14,54 @@ func GenerateFieldsMap(fieldNames []string, fieldValues []string) map[string]str return nil } } + +func GenerateLookupTableFields(fieldNames []string, fieldTypes []string) []types.LookupTableField { + if len(fieldNames) > 0 && len(fieldTypes) > 0 { + fields := []types.LookupTableField{} + for i, _ := range fieldNames { + field := types.LookupTableField{ + FieldName: fieldNames[i], + FieldType: fieldTypes[i], + } + fields = append(fields, field) + i++ + } + return fields + } else { + return nil + } +} + +func GenerateLookupTableColumns(columnNames []string, columnValues []string) []types.TableRow { + if len(columnNames) > 0 && len(columnValues) > 0 { + fields := []types.TableRow{} + for i, _ := range columnNames { + field := types.TableRow{ + ColumnName: columnNames[i], + ColumnValue: columnValues[i], + } + fields = append(fields, field) + i++ + } + return fields + } else { + return nil + } +} + +func GenerateCidrList(ipAddresses []string, descriptions []string) types.CidrList { + addressList := types.CidrList{} + if len(ipAddresses) > 0 { + for i, _ := range ipAddresses { + address := types.Cidr{ + Cidr: ipAddresses[i], + Description: descriptions[i], + } + addressList.Data = append(addressList.Data, address) + i++ + } + return addressList + } else { + return addressList + } +} diff --git a/pkg/cmdutils/output.go b/pkg/cmdutils/output.go index 0415ea39..20103dfb 100644 --- a/pkg/cmdutils/output.go +++ b/pkg/cmdutils/output.go @@ -12,7 +12,7 @@ func Output(apiResponse interface{}, httpResponse *http.Response, errorResponse fmt.Println("failed to marshal api response") } if apiResponse == nil { - if httpResponse.StatusCode != 204 { + if httpResponse.StatusCode != 204 && httpResponse.StatusCode != 200 { fmt.Println(errorResponse) } else { fmt.Println(message) diff --git a/pkg/logging/log.go b/pkg/logging/log.go index 4920b6f5..5daa067a 100644 --- a/pkg/logging/log.go +++ b/pkg/logging/log.go @@ -31,22 +31,3 @@ func GetConsoleLogger() zerolog.Logger { log := zerolog.New(output).With().Timestamp().Logger() return log } - -// GetLogger -// Used to create an instance of zerlog.logger that can be used with commands using the new Sumo Logic Go SDK -func GetLogger() *zerolog.Logger { - useColour := true - if runtime.GOOS == "windows" { - useColour = false - } - output := zerolog.ConsoleWriter{ - Out: os.Stdout, - TimeFormat: time.RFC3339, - NoColor: useColour, - } - output.FormatLevel = func(i interface{}) string { - return strings.ToUpper(fmt.Sprintf("| %-6s|", i)) - } - log := zerolog.New(output).With().Timestamp().Logger() - return &log -} diff --git a/scripts/build.sh b/scripts/build.sh new file mode 100644 index 00000000..a5420163 --- /dev/null +++ b/scripts/build.sh @@ -0,0 +1,14 @@ +#!/bin/sh + +echo "=> Downloading go dependencies" +go mod download + +echo "=> Installing gox" +go get github.com/mitchellh/gox + +if [ "$DEV" = "true" ]; then + echo "=> Building sumocli" + gox -osarch="linux/amd64" ./cmd/sumocli + ls -lah + mv "$GOPATH/src/github.com/wizedkyle/sumocli/sumocli_linux_amd64" "$GOPATH/bin/sumocli" +fi diff --git a/sumocli b/sumocli new file mode 100755 index 00000000..50c577a8 Binary files /dev/null and b/sumocli differ