From 24245e46e885854cefa8165674b8db2353981fa5 Mon Sep 17 00:00:00 2001 From: Paul Payne Date: Sat, 11 Oct 2025 17:19:11 +0000 Subject: [PATCH] Initial commit. --- .gitignore | 24 ++ LICENSE | 661 ++++++++++++++++++++++++++++++ README.md | 17 + cmd/app.go | 186 +++++++++ cmd/backup.go | 55 +++ cmd/cluster.go | 284 +++++++++++++ cmd/commands.go | 1 + cmd/config.go | 93 +++++ cmd/daemon.go | 67 +++ cmd/instance.go | 276 +++++++++++++ cmd/node.go | 482 ++++++++++++++++++++++ cmd/operation.go | 142 +++++++ cmd/pxe.go | 78 ++++ cmd/root.go | 132 ++++++ cmd/secret.go | 72 ++++ cmd/service.go | 325 +++++++++++++++ cmd/utility.go | 68 +++ cmd/version.go | 38 ++ docs/setup.md | 143 +++++++ go.mod | 28 ++ go.sum | 67 +++ install-man-page.sh | 14 + internal/client/client.go | 152 +++++++ internal/config/config.go | 17 + internal/config/example_test.go | 44 ++ internal/config/instance.go | 83 ++++ internal/config/instance_test.go | 210 ++++++++++ internal/config/validator.go | 61 +++ internal/config/validator_test.go | 153 +++++++ internal/prompt/example_test.go | 73 ++++ internal/prompt/prompt.go | 89 ++++ internal/prompt/prompt_test.go | 64 +++ main.go | 7 + 33 files changed, 4206 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 cmd/app.go create mode 100644 cmd/backup.go create mode 100644 cmd/cluster.go create mode 100644 cmd/commands.go create mode 100644 cmd/config.go create mode 100644 cmd/daemon.go create mode 100644 cmd/instance.go create mode 100644 cmd/node.go create mode 100644 cmd/operation.go create mode 100644 cmd/pxe.go create mode 100644 cmd/root.go create mode 100644 cmd/secret.go create mode 100644 cmd/service.go create mode 100644 cmd/utility.go create mode 100644 cmd/version.go create mode 100644 docs/setup.md create mode 100644 go.mod create mode 100644 go.sum create mode 100755 install-man-page.sh create mode 100644 internal/client/client.go create mode 100644 internal/config/config.go create mode 100644 internal/config/example_test.go create mode 100644 internal/config/instance.go create mode 100644 internal/config/instance_test.go create mode 100644 internal/config/validator.go create mode 100644 internal/config/validator_test.go create mode 100644 internal/prompt/example_test.go create mode 100644 internal/prompt/prompt.go create mode 100644 internal/prompt/prompt_test.go create mode 100644 main.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1c0f488 --- /dev/null +++ b/.gitignore @@ -0,0 +1,24 @@ +# Cli build artifacts +build/ +dist/ +wild +*.deb +__debug* + +# Go build cache +*.o +*.a +*.so +__debug* + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool +*.out +*.cover +*.coverage + +# Go workspace file +go.work +go.work.sum diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0ad25db --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..876d807 --- /dev/null +++ b/README.md @@ -0,0 +1,17 @@ +# Wild CLI + +The Wild CLI is a command-line interface for advanced users who prefer to manage Wild Cloud from the terminal. It communicates with the Wild Central Daemon (wildd) to perform actions. + +## Usage + +```bash +wild --help +``` + +## Development + +```bash +make build +build/wild --help +``` + diff --git a/cmd/app.go b/cmd/app.go new file mode 100644 index 0000000..f9f97cb --- /dev/null +++ b/cmd/app.go @@ -0,0 +1,186 @@ +package cmd + +import ( + "fmt" + + "github.com/spf13/cobra" +) + +// App commands +var appCmd = &cobra.Command{ + Use: "app", + Short: "Manage applications", +} + +var appListCmd = &cobra.Command{ + Use: "list", + Short: "List available apps", + RunE: func(cmd *cobra.Command, args []string) error { + resp, err := apiClient.Get("/api/v1/apps") + if err != nil { + return err + } + + if outputFormat == "json" { + return printJSON(resp.Data) + } + + apps := resp.GetArray("apps") + if len(apps) == 0 { + fmt.Println("No apps found") + return nil + } + + fmt.Printf("%-20s %-30s\n", "NAME", "DESCRIPTION") + fmt.Println("-----------------------------------------------------") + for _, app := range apps { + if m, ok := app.(map[string]interface{}); ok { + fmt.Printf("%-20s %-30s\n", m["name"], m["description"]) + } + } + return nil + }, +} + +var appListDeployedCmd = &cobra.Command{ + Use: "list-deployed", + Short: "List deployed apps", + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/apps", inst)) + if err != nil { + return err + } + + if outputFormat == "json" { + return printJSON(resp.Data) + } + + apps := resp.GetArray("apps") + if len(apps) == 0 { + fmt.Println("No deployed apps found") + return nil + } + + fmt.Printf("%-20s %-12s\n", "NAME", "STATUS") + fmt.Println("----------------------------------") + for _, app := range apps { + if m, ok := app.(map[string]interface{}); ok { + fmt.Printf("%-20s %-12s\n", m["name"], m["status"]) + } + } + return nil + }, +} + +var appAddCmd = &cobra.Command{ + Use: "add ", + Short: "Add app to instance", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + _, err = apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/apps", inst), map[string]string{ + "name": args[0], + }) + if err != nil { + return err + } + + fmt.Printf("App added: %s\n", args[0]) + return nil + }, +} + +var appDeployCmd = &cobra.Command{ + Use: "deploy ", + Short: "Deploy an app", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + resp, err := apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/apps/%s/deploy", inst, args[0]), nil) + if err != nil { + return err + } + + fmt.Printf("App deployment started: %s\n", args[0]) + if opID := resp.GetString("operation_id"); opID != "" { + fmt.Printf("Operation ID: %s\n", opID) + } + return nil + }, +} + +var appDeleteCmd = &cobra.Command{ + Use: "delete ", + Short: "Delete an app", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + _, err = apiClient.Delete(fmt.Sprintf("/api/v1/instances/%s/apps/%s", inst, args[0])) + if err != nil { + return err + } + + fmt.Printf("App deleted: %s\n", args[0]) + return nil + }, +} + +var appStatusCmd = &cobra.Command{ + Use: "status ", + Short: "Get app status", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/apps/%s/status", inst, args[0])) + if err != nil { + return err + } + + if outputFormat == "json" { + return printJSON(resp.Data) + } + + // Print status in text format + fmt.Printf("App: %s\n", resp.GetString("name")) + fmt.Printf("Status: %s\n", resp.GetString("status")) + if version := resp.GetString("version"); version != "" { + fmt.Printf("Version: %s\n", version) + } + fmt.Printf("Namespace: %s\n", resp.GetString("namespace")) + if url := resp.GetString("url"); url != "" { + fmt.Printf("URL: %s\n", url) + } + return nil + }, +} + +func init() { + appCmd.AddCommand(appListCmd) + appCmd.AddCommand(appListDeployedCmd) + appCmd.AddCommand(appAddCmd) + appCmd.AddCommand(appDeployCmd) + appCmd.AddCommand(appDeleteCmd) + appCmd.AddCommand(appStatusCmd) +} + diff --git a/cmd/backup.go b/cmd/backup.go new file mode 100644 index 0000000..6406626 --- /dev/null +++ b/cmd/backup.go @@ -0,0 +1,55 @@ +package cmd + +import ( + "fmt" + + "github.com/spf13/cobra" +) + +// Backup/Restore commands +var backupCmd = &cobra.Command{ + Use: "backup ", + Short: "Backup an app", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + resp, err := apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/apps/%s/backup", inst, args[0]), nil) + if err != nil { + return err + } + + fmt.Printf("Backup started: %s\n", args[0]) + if opID := resp.GetString("operation_id"); opID != "" { + fmt.Printf("Operation ID: %s\n", opID) + } + return nil + }, +} + +var restoreCmd = &cobra.Command{ + Use: "restore ", + Short: "Restore an app", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + resp, err := apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/apps/%s/restore", inst, args[0]), nil) + if err != nil { + return err + } + + fmt.Printf("Restore started: %s\n", args[0]) + if opID := resp.GetString("operation_id"); opID != "" { + fmt.Printf("Operation ID: %s\n", opID) + } + return nil + }, +} + diff --git a/cmd/cluster.go b/cmd/cluster.go new file mode 100644 index 0000000..4fa999c --- /dev/null +++ b/cmd/cluster.go @@ -0,0 +1,284 @@ +package cmd + +import ( + "fmt" + "os" + + "github.com/spf13/cobra" + + "github.com/wild-cloud/wild-central/wild/internal/config" +) + +// Cluster commands +var clusterCmd = &cobra.Command{ + Use: "cluster", + Short: "Manage cluster", +} + +var clusterBootstrapCmd = &cobra.Command{ + Use: "bootstrap ", + Short: "Bootstrap cluster on a control plane node", + Long: `Bootstrap the Kubernetes cluster by initializing etcd on a control plane node. + +This should be run once after the first control plane node is configured. + +Example: + wild cluster bootstrap test-control-1`, + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + nodeName := args[0] + + resp, err := apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/cluster/bootstrap", inst), map[string]string{ + "node": nodeName, + }) + if err != nil { + return err + } + + fmt.Printf("Cluster bootstrap started on node: %s\n", nodeName) + if opID := resp.GetString("operation_id"); opID != "" { + fmt.Printf("Operation ID: %s\n", opID) + } + return nil + }, +} + +var clusterStatusCmd = &cobra.Command{ + Use: "status", + Short: "Get cluster status", + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/cluster/status", inst)) + if err != nil { + return err + } + + if outputFormat == "json" { + return printJSON(resp.Data) + } + + return printYAML(resp.Data) + }, +} + +var clusterHealthCmd = &cobra.Command{ + Use: "health", + Short: "Check cluster health", + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/cluster/health", inst)) + if err != nil { + return err + } + + if outputFormat == "json" { + return printJSON(resp.Data) + } + + return printYAML(resp.GetMap("health")) + }, +} + +var clusterKubeconfigCmd = &cobra.Command{ + Use: "kubeconfig", + Short: "Get or generate kubeconfig", + Long: `Get the cluster kubeconfig or regenerate it from the cluster. + +By default, retrieves the existing kubeconfig file. Use --generate to +regenerate it from the cluster (useful if the file was lost or corrupted). + +Examples: + wild cluster kubeconfig # Get existing kubeconfig + wild cluster kubeconfig --persist # Get and save locally + wild cluster kubeconfig --generate # Regenerate from cluster + wild cluster kubeconfig --generate --persist # Regenerate and save locally`, + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + persist, _ := cmd.Flags().GetBool("persist") + generate, _ := cmd.Flags().GetBool("generate") + + var kubeconfigContent string + + // If --generate flag is set, trigger regeneration + if generate { + fmt.Println("Regenerating kubeconfig from cluster...") + _, err := apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/cluster/kubeconfig/generate", inst), nil) + if err != nil { + return err + } + fmt.Println("Kubeconfig regenerated successfully") + + // Now fetch the newly generated kubeconfig + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/cluster/kubeconfig", inst)) + if err != nil { + return err + } + kubeconfigContent = resp.GetString("kubeconfig") + } else { + // Get existing kubeconfig + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/cluster/kubeconfig", inst)) + if err != nil { + return err + } + kubeconfigContent = resp.GetString("kubeconfig") + } + + // If --persist flag is set, save to instance directory + if persist { + dataDir := config.GetWildCLIDataDir() + instanceDir := fmt.Sprintf("%s/instances/%s", dataDir, inst) + + // Create instance directory if it doesn't exist + if err := os.MkdirAll(instanceDir, 0755); err != nil { + return fmt.Errorf("failed to create instance directory: %w", err) + } + + kubeconfigPath := fmt.Sprintf("%s/kubeconfig", instanceDir) + if err := os.WriteFile(kubeconfigPath, []byte(kubeconfigContent), 0600); err != nil { + return fmt.Errorf("failed to write kubeconfig: %w", err) + } + + fmt.Printf("Kubeconfig saved to %s\n", kubeconfigPath) + return nil + } + + // Default behavior: print to stdout + fmt.Println(kubeconfigContent) + return nil + }, +} + +var clusterConfigGenerateCmd = &cobra.Command{ + Use: "config generate", + Short: "Generate cluster configuration", + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + resp, err := apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/cluster/config/generate", inst), nil) + if err != nil { + return err + } + + fmt.Println("Cluster configuration generated successfully") + if msg := resp.GetString("message"); msg != "" { + fmt.Println(msg) + } + return nil + }, +} + +var clusterTalosconfigCmd = &cobra.Command{ + Use: "talosconfig", + Short: "Get talosconfig", + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + persist, _ := cmd.Flags().GetBool("persist") + + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/cluster/talosconfig", inst)) + if err != nil { + return err + } + + talosconfigContent := resp.GetString("talosconfig") + + // If --persist flag is set, save to instance directory + if persist { + dataDir := config.GetWildCLIDataDir() + instanceDir := fmt.Sprintf("%s/instances/%s", dataDir, inst) + + // Create instance directory if it doesn't exist + if err := os.MkdirAll(instanceDir, 0755); err != nil { + return fmt.Errorf("failed to create instance directory: %w", err) + } + + talosconfigPath := fmt.Sprintf("%s/talosconfig", instanceDir) + if err := os.WriteFile(talosconfigPath, []byte(talosconfigContent), 0600); err != nil { + return fmt.Errorf("failed to write talosconfig: %w", err) + } + + fmt.Printf("Talosconfig saved to %s\n", talosconfigPath) + return nil + } + + // Default behavior: print to stdout + fmt.Println(talosconfigContent) + return nil + }, +} + +var clusterEndpointsCmd = &cobra.Command{ + Use: "endpoints", + Short: "Configure cluster endpoints to use VIP", + Long: `Configure talosconfig endpoints to use the control plane VIP. + +Run this after all control plane nodes are added and running. +This updates the talosconfig to use the VIP as the primary endpoint +and retrieves the kubeconfig for cluster access. + +Examples: + # Configure endpoints to use VIP only + wild cluster endpoints + + # Include all control node IPs as fallback endpoints + wild cluster endpoints --nodes`, + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + includeNodes, _ := cmd.Flags().GetBool("nodes") + + _, err = apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/cluster/endpoints", inst), map[string]bool{ + "include_nodes": includeNodes, + }) + if err != nil { + return err + } + + fmt.Println("āœ“ Endpoints configured to use control plane VIP") + return nil + }, +} + +func init() { + clusterCmd.AddCommand(clusterBootstrapCmd) + clusterCmd.AddCommand(clusterStatusCmd) + clusterCmd.AddCommand(clusterHealthCmd) + clusterCmd.AddCommand(clusterKubeconfigCmd) + clusterCmd.AddCommand(clusterConfigGenerateCmd) + clusterCmd.AddCommand(clusterTalosconfigCmd) + clusterCmd.AddCommand(clusterEndpointsCmd) + + clusterEndpointsCmd.Flags().Bool("nodes", false, "Include all control node IPs as fallback endpoints") + + // Add --persist flags to config commands + clusterTalosconfigCmd.Flags().Bool("persist", false, "Save talosconfig to instance directory") + clusterKubeconfigCmd.Flags().Bool("persist", false, "Save kubeconfig to instance directory") + clusterKubeconfigCmd.Flags().Bool("generate", false, "Regenerate kubeconfig from the cluster") +} + diff --git a/cmd/commands.go b/cmd/commands.go new file mode 100644 index 0000000..1d619dd --- /dev/null +++ b/cmd/commands.go @@ -0,0 +1 @@ +package cmd diff --git a/cmd/config.go b/cmd/config.go new file mode 100644 index 0000000..c04fd88 --- /dev/null +++ b/cmd/config.go @@ -0,0 +1,93 @@ +package cmd + +import ( + "fmt" + + "github.com/spf13/cobra" + + "github.com/wild-cloud/wild-central/wild/internal/config" +) + +// Config commands +var configCmd = &cobra.Command{ + Use: "config", + Short: "Manage instance configuration", +} + +var configGetCmd = &cobra.Command{ + Use: "get ", + Short: "Get configuration value", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + key := args[0] + + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/config", inst)) + if err != nil { + return err + } + + // Use nested path lookup for dot notation (e.g., certManager.cloudflare.zoneId) + val := config.GetValue(resp.Data, key) + if val != nil { + fmt.Println(val) + } else { + return fmt.Errorf("key '%s' not found", key) + } + return nil + }, +} + +var configSetCmd = &cobra.Command{ + Use: "set ", + Short: "Set configuration value", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + key, value := args[0], args[1] + + _, err = apiClient.Put(fmt.Sprintf("/api/v1/instances/%s/config", inst), map[string]string{ + key: value, + }) + if err != nil { + return err + } + + fmt.Printf("Configuration updated: %s = %s\n", key, value) + return nil + }, +} + +var configShowCmd = &cobra.Command{ + Use: "show", + Short: "Show full configuration", + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/config", inst)) + if err != nil { + return err + } + + if outputFormat == "json" { + return printJSON(resp.Data) + } + + return printYAML(resp.Data) + }, +} + +func init() { + configCmd.AddCommand(configGetCmd) + configCmd.AddCommand(configSetCmd) + configCmd.AddCommand(configShowCmd) +} diff --git a/cmd/daemon.go b/cmd/daemon.go new file mode 100644 index 0000000..01b6d8f --- /dev/null +++ b/cmd/daemon.go @@ -0,0 +1,67 @@ +package cmd + +import ( + "fmt" + + "github.com/spf13/cobra" +) + +var daemonCmd = &cobra.Command{ + Use: "daemon", + Short: "Daemon operations", + Long: `Check daemon status and perform daemon-related operations.`, +} + +var daemonStatusCmd = &cobra.Command{ + Use: "status", + Short: "Check daemon status", + Long: `Check if the Wild Central daemon is running and accessible.`, + RunE: func(cmd *cobra.Command, args []string) error { + // Try to get status from daemon + resp, err := apiClient.Get("/api/v1/status") + if err != nil { + return fmt.Errorf("daemon is not accessible: %w", err) + } + + if outputFormat == "json" { + return printJSON(resp.Data) + } + + if outputFormat == "yaml" { + return printYAML(resp.Data) + } + + // Print status + fmt.Println("āœ“ Daemon is running") + fmt.Printf(" URL: %s\n", apiClient.BaseURL()) + + if version := resp.GetString("version"); version != "" { + fmt.Printf(" Version: %s\n", version) + } + + if uptime := resp.GetString("uptime"); uptime != "" { + fmt.Printf(" Uptime: %s\n", uptime) + } + + if dataDir := resp.GetString("dataDir"); dataDir != "" { + fmt.Printf(" Data Directory: %s\n", dataDir) + } + + if directoryPath := resp.GetString("directoryPath"); directoryPath != "" { + fmt.Printf(" Wild Directory: %s\n", directoryPath) + } + + // Show instance info + if instances := resp.GetMap("instances"); instances != nil { + if count, ok := instances["count"].(float64); ok { + fmt.Printf(" Instances: %d\n", int(count)) + } + } + + return nil + }, +} + +func init() { + daemonCmd.AddCommand(daemonStatusCmd) +} diff --git a/cmd/instance.go b/cmd/instance.go new file mode 100644 index 0000000..b7e4a8e --- /dev/null +++ b/cmd/instance.go @@ -0,0 +1,276 @@ +package cmd + +import ( + "fmt" + "os" + "path/filepath" + + "github.com/spf13/cobra" + + "github.com/wild-cloud/wild-central/wild/internal/config" +) + +var instanceCmd = &cobra.Command{ + Use: "instance", + Short: "Manage instances", + Long: `Create, list, and manage Wild Cloud instances.`, +} + +var instanceCreateCmd = &cobra.Command{ + Use: "create ", + Short: "Create a new instance", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + name := args[0] + + resp, err := apiClient.Post("/api/v1/instances", map[string]string{ + "name": name, + }) + if err != nil { + return err + } + + fmt.Printf("Instance '%s' created successfully\n", name) + if msg, ok := resp.Data["message"].(string); ok && msg != "" { + fmt.Println(msg) + } + return nil + }, +} + +var instanceListCmd = &cobra.Command{ + Use: "list", + Short: "List all instances", + RunE: func(cmd *cobra.Command, args []string) error { + resp, err := apiClient.Get("/api/v1/instances") + if err != nil { + return err + } + + if outputFormat == "json" { + return printJSON(resp.Data) + } + + if outputFormat == "yaml" { + return printYAML(resp.Data) + } + + instances := resp.GetArray("instances") + if len(instances) == 0 { + fmt.Println("No instances found") + return nil + } + + fmt.Println("INSTANCES:") + for _, inst := range instances { + if name, ok := inst.(string); ok { + fmt.Printf(" - %s\n", name) + } + } + return nil + }, +} + +var instanceShowCmd = &cobra.Command{ + Use: "show ", + Short: "Show instance details", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + name := args[0] + + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s", name)) + if err != nil { + return err + } + + if outputFormat == "json" { + return printJSON(resp.Data) + } + + if outputFormat == "yaml" { + return printYAML(resp.Data) + } + + // Pretty print instance info + instanceName := resp.GetString("name") + if instanceName != "" { + fmt.Printf("Instance: %s\n", instanceName) + } + + // Show key config values + if config := resp.GetMap("config"); config != nil { + // Check for cloud config (test-cloud structure) + if cloud, ok := config["cloud"].(map[string]interface{}); ok { + if domain, ok := cloud["domain"].(string); ok && domain != "" { + fmt.Printf("Domain: %s\n", domain) + } + if baseDomain, ok := cloud["baseDomain"].(string); ok && baseDomain != "" { + fmt.Printf("Base Domain: %s\n", baseDomain) + } + } else { + // Check for direct config fields (test-cli structure) + if domain, ok := config["domain"].(string); ok && domain != "" { + fmt.Printf("Domain: %s\n", domain) + } + if baseDomain, ok := config["baseDomain"].(string); ok && baseDomain != "" { + fmt.Printf("Base Domain: %s\n", baseDomain) + } + } + + // Show cluster info if available + if cluster, ok := config["cluster"].(map[string]interface{}); ok { + if clusterName, ok := cluster["name"].(string); ok && clusterName != "" { + fmt.Printf("Cluster Name: %s\n", clusterName) + } + } + } + + fmt.Println("\nUse -o json or -o yaml for full configuration") + return nil + }, +} + +var instanceDeleteCmd = &cobra.Command{ + Use: "delete ", + Short: "Delete an instance", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + name := args[0] + + // Confirm deletion + fmt.Printf("Are you sure you want to delete instance '%s'? (yes/no): ", name) + var confirm string + fmt.Scanln(&confirm) + if confirm != "yes" { + fmt.Println("Deletion cancelled") + return nil + } + + resp, err := apiClient.Delete(fmt.Sprintf("/api/v1/instances/%s", name)) + if err != nil { + return err + } + + fmt.Printf("Instance '%s' deleted successfully\n", name) + if msg, ok := resp.Data["message"].(string); ok && msg != "" { + fmt.Println(msg) + } + return nil + }, +} + +var instanceCurrentCmd = &cobra.Command{ + Use: "current", + Short: "Show current instance", + Long: `Display the instance that would be used by commands. + +Resolution order: + 1. --instance flag + 2. ~/.wildcloud/current_instance file + 3. Auto-select first available instance`, + Run: func(cmd *cobra.Command, args []string) { + inst, err := getInstanceName() + if err != nil { + fmt.Printf("Error: %v\n", err) + os.Exit(1) + } + + fmt.Println(inst) + }, +} + +var instanceUseCmd = &cobra.Command{ + Use: "use ", + Short: "Set the default instance", + Long: `Set the default instance to use for all commands. + +This persists the instance selection to ~/.wildcloud/current_instance. +The instance can still be overridden with the --instance flag.`, + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + instanceToSet := args[0] + + // Validate instance exists by calling API + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s", instanceToSet)) + if err != nil { + return fmt.Errorf("instance '%s' not found: %w", instanceToSet, err) + } + + // Verify we got a valid response + if name := resp.GetString("name"); name != instanceToSet { + return fmt.Errorf("instance '%s' not found", instanceToSet) + } + + // Persist the selection + if err := config.SetCurrentInstance(instanceToSet); err != nil { + return fmt.Errorf("failed to set current instance: %w", err) + } + + fmt.Printf("Switched to instance: %s\n", instanceToSet) + + // Check for config files and provide hint + dataDir := config.GetWildCLIDataDir() + instanceDir := filepath.Join(dataDir, "instances", instanceToSet) + + var hasConfigs bool + if _, err := os.Stat(filepath.Join(instanceDir, "talosconfig")); err == nil { + hasConfigs = true + } + if _, err := os.Stat(filepath.Join(instanceDir, "kubeconfig")); err == nil { + hasConfigs = true + } + + if hasConfigs { + fmt.Println("\nTo configure your environment, run:") + fmt.Println(" source <(wild instance env)") + } + + return nil + }, +} + +var instanceEnvCmd = &cobra.Command{ + Use: "env", + Short: "Output environment variables for current instance", + Long: `Output export commands for TALOSCONFIG and KUBECONFIG. + +Usage: + source <(wild instance env) + +This will set environment variables for the current instance's talosconfig and kubeconfig files if they exist.`, + RunE: func(cmd *cobra.Command, args []string) error { + // Get current instance + inst, err := getInstanceName() + if err != nil { + return err + } + + // Check for talosconfig and kubeconfig files + dataDir := config.GetWildCLIDataDir() + instanceDir := filepath.Join(dataDir, "instances", inst) + + // Check for talosconfig + talosconfigPath := filepath.Join(instanceDir, "talosconfig") + if _, err := os.Stat(talosconfigPath); err == nil { + fmt.Printf("export TALOSCONFIG=%s\n", talosconfigPath) + } + + // Check for kubeconfig + kubeconfigPath := filepath.Join(instanceDir, "kubeconfig") + if _, err := os.Stat(kubeconfigPath); err == nil { + fmt.Printf("export KUBECONFIG=%s\n", kubeconfigPath) + } + + return nil + }, +} + +func init() { + instanceCmd.AddCommand(instanceCreateCmd) + instanceCmd.AddCommand(instanceListCmd) + instanceCmd.AddCommand(instanceShowCmd) + instanceCmd.AddCommand(instanceDeleteCmd) + instanceCmd.AddCommand(instanceCurrentCmd) + instanceCmd.AddCommand(instanceUseCmd) + instanceCmd.AddCommand(instanceEnvCmd) +} diff --git a/cmd/node.go b/cmd/node.go new file mode 100644 index 0000000..c3542a0 --- /dev/null +++ b/cmd/node.go @@ -0,0 +1,482 @@ +package cmd + +import ( + "fmt" + "time" + + "github.com/spf13/cobra" +) + +// Node commands +var nodeCmd = &cobra.Command{ + Use: "node", + Short: "Manage nodes", +} + +var nodeDiscoverCmd = &cobra.Command{ + Use: "discover ...", + Short: "Discover nodes on network", + Long: "Discover nodes on the network by scanning the provided IP addresses or ranges", + Args: cobra.MinimumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + fmt.Printf("Starting discovery for %d IP(s)...\n", len(args)) + _, err = apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/nodes/discover", inst), map[string]interface{}{ + "ip_list": args, + }) + if err != nil { + return err + } + + // Poll for completion + fmt.Println("Scanning nodes...") + for { + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/discovery", inst)) + if err != nil { + return err + } + + active, _ := resp.Data["active"].(bool) + if !active { + // Discovery complete + nodesFound := resp.GetArray("nodes_found") + if len(nodesFound) == 0 { + fmt.Println("\nNo Talos nodes found") + return nil + } + + fmt.Printf("\nFound %d node(s):\n\n", len(nodesFound)) + fmt.Printf("%-15s %-12s %-10s\n", "IP", "INTERFACE", "VERSION") + fmt.Println("-----------------------------------------------") + for _, node := range nodesFound { + if m, ok := node.(map[string]interface{}); ok { + fmt.Printf("%-15s %-12s %-10s\n", + m["ip"], m["interface"], m["version"]) + } + } + return nil + } + + // Still running, wait a bit + fmt.Print(".") + time.Sleep(500 * time.Millisecond) + } + }, +} + +var nodeDetectCmd = &cobra.Command{ + Use: "detect ", + Short: "Detect hardware on a single node", + Long: `Detect hardware configuration on a single node in maintenance mode. + +This queries the node for available network interfaces and disks, helping you +decide which hardware to use when adding the node to the cluster. + +Example: + wild node detect 192.168.1.31 + +Output shows: + - Available network interfaces + - Available disks with sizes + - Recommended selections`, + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + nodeIP := args[0] + + // Call API to detect hardware + resp, err := apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/nodes/detect", inst), map[string]string{ + "ip": nodeIP, + }) + if err != nil { + return err + } + + if outputFormat == "json" { + return printJSON(resp.Data) + } + + if outputFormat == "yaml" { + return printYAML(resp.Data) + } + + // Text format - show hardware details + fmt.Printf("Hardware detected for node at %s:\n\n", nodeIP) + + if iface := resp.GetString("interface"); iface != "" { + fmt.Printf("Interface: %s\n", iface) + } + + if disks := resp.GetArray("disks"); len(disks) > 0 { + fmt.Printf("\nAvailable Disks:\n") + for _, diskData := range disks { + diskMap, ok := diskData.(map[string]interface{}) + if !ok { + continue + } + + path, _ := diskMap["path"].(string) + size, _ := diskMap["size"].(float64) // JSON numbers are float64 + + // Format size in GB/TB + sizeGB := size / (1024 * 1024 * 1024) + var sizeStr string + if sizeGB >= 1000 { + sizeStr = fmt.Sprintf("%.1f TB", sizeGB/1024) + } else { + sizeStr = fmt.Sprintf("%.1f GB", sizeGB) + } + + fmt.Printf(" - %s (%s)\n", path, sizeStr) + } + } + + if selected := resp.GetString("selected_disk"); selected != "" { + fmt.Printf("\nRecommended Disk: %s\n", selected) + } + + fmt.Printf("\nTo add this node:\n") + fmt.Printf(" wild node add --current-ip %s --target-ip --disk --interface \n", nodeIP) + + return nil + }, +} + +var nodeListCmd = &cobra.Command{ + Use: "list", + Short: "List configured nodes", + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/nodes", inst)) + if err != nil { + return err + } + + if outputFormat == "json" { + return printJSON(resp.Data) + } + + if outputFormat == "yaml" { + return printYAML(resp.Data) + } + + nodes := resp.GetArray("nodes") + if len(nodes) == 0 { + fmt.Println("No nodes found") + return nil + } + + fmt.Printf("%-20s %-12s %-15s\n", "HOSTNAME", "ROLE", "TARGET IP") + fmt.Println("-----------------------------------------------------") + for _, node := range nodes { + if m, ok := node.(map[string]interface{}); ok { + fmt.Printf("%-20s %-12s %-15s\n", + m["hostname"], m["role"], m["target_ip"]) + } + } + return nil + }, +} + +var nodeShowCmd = &cobra.Command{ + Use: "show ", + Short: "Show node details", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/nodes/%s", inst, args[0])) + if err != nil { + return err + } + + if outputFormat == "json" { + return printJSON(resp.Data) + } + + if outputFormat == "yaml" { + return printYAML(resp.Data) + } + + // Text format - show node details + fmt.Printf("Hostname: %s\n", resp.GetString("hostname")) + fmt.Printf("Role: %s\n", resp.GetString("role")) + fmt.Printf("Target IP: %s\n", resp.GetString("target_ip")) + fmt.Printf("Disk: %s\n", resp.GetString("disk")) + fmt.Printf("Interface: %s\n", resp.GetString("interface")) + fmt.Printf("Version: %s\n", resp.GetString("version")) + fmt.Printf("Schematic ID: %s\n", resp.GetString("schematic_id")) + fmt.Printf("Configured: %v\n", resp.Data["configured"]) + fmt.Printf("Deployed: %v\n", resp.Data["deployed"]) + + return nil + }, +} + +var nodeAddCmd = &cobra.Command{ + Use: "add ", + Short: "Add a node to cluster configuration", + Long: `Add a node to the cluster configuration with required hardware details. + +Role must be either 'controlplane' or 'worker'. + +The node configuration will be stored in the instance config and used during apply. + +Examples: + # Node in maintenance mode (PXE booted) + wild node add control-1 controlplane --current-ip 192.168.1.100 --target-ip 192.168.1.31 --disk /dev/sda + + # Node already applied (unusual, only if config was removed manually) + wild node add worker-1 worker --target-ip 192.168.1.32 --disk /dev/nvme0n1`, + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + // Get flags + targetIP, _ := cmd.Flags().GetString("target-ip") + currentIP, _ := cmd.Flags().GetString("current-ip") + disk, _ := cmd.Flags().GetString("disk") + iface, _ := cmd.Flags().GetString("interface") + schematicID, _ := cmd.Flags().GetString("schematic-id") + maintenance, _ := cmd.Flags().GetBool("maintenance") + + // Build request body + body := map[string]interface{}{ + "hostname": args[0], + "role": args[1], + } + + if targetIP != "" { + body["target_ip"] = targetIP + } + if currentIP != "" { + body["current_ip"] = currentIP + } + if disk != "" { + body["disk"] = disk + } + if iface != "" { + body["interface"] = iface + } + if schematicID != "" { + body["schematic_id"] = schematicID + } + if maintenance { + body["maintenance"] = true + } + + _, err = apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/nodes", inst), body) + if err != nil { + return err + } + + fmt.Printf("Node added: %s (%s)\n", args[0], args[1]) + if targetIP != "" { + fmt.Printf(" Target IP: %s\n", targetIP) + } + if disk != "" { + fmt.Printf(" Disk: %s\n", disk) + } + return nil + }, +} + +var nodeApplyCmd = &cobra.Command{ + Use: "apply ", + Short: "Apply Talos configuration to node", + Long: `Generate and apply Talos configuration to a node. + +This command: +1. Auto-fetches patch templates if missing +2. Generates node-specific configuration from templates +3. Merges base config with node patch +4. Applies configuration to node (using --insecure if in maintenance mode) +5. Updates node state after successful application + +Examples: + # Apply to node in maintenance mode (PXE booted) + wild node apply control-1 + + # Re-apply to production node (updates configuration) + wild node apply worker-1`, + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + resp, err := apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/nodes/%s/apply", inst, args[0]), nil) + if err != nil { + return err + } + + fmt.Printf("Node configuration applied: %s\n", args[0]) + if msg := resp.GetString("message"); msg != "" { + fmt.Printf("%s\n", msg) + } + return nil + }, +} + +var nodeUpdateCmd = &cobra.Command{ + Use: "update ", + Short: "Update node configuration", + Long: `Update existing node configuration with partial updates. + +This command modifies node properties without requiring all fields. + +Examples: + # Update disk after hardware change + wild node update worker-1 --disk /dev/sdb + + # Move node to maintenance mode + wild node update control-1 --current-ip 192.168.1.100 --maintenance + + # Clear maintenance after successful apply + wild node update control-1 --no-maintenance`, + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + // Get flags + targetIP, _ := cmd.Flags().GetString("target-ip") + currentIP, _ := cmd.Flags().GetString("current-ip") + disk, _ := cmd.Flags().GetString("disk") + iface, _ := cmd.Flags().GetString("interface") + schematicID, _ := cmd.Flags().GetString("schematic-id") + maintenance, _ := cmd.Flags().GetBool("maintenance") + noMaintenance, _ := cmd.Flags().GetBool("no-maintenance") + + // Build request body with only provided fields + body := map[string]interface{}{} + + if targetIP != "" { + body["target_ip"] = targetIP + } + if currentIP != "" { + body["current_ip"] = currentIP + } + if disk != "" { + body["disk"] = disk + } + if iface != "" { + body["interface"] = iface + } + if schematicID != "" { + body["schematic_id"] = schematicID + } + if maintenance { + body["maintenance"] = true + } + if noMaintenance { + body["maintenance"] = false + } + + if len(body) == 0 { + return fmt.Errorf("no updates specified") + } + + _, err = apiClient.Put(fmt.Sprintf("/api/v1/instances/%s/nodes/%s", inst, args[0]), body) + if err != nil { + return err + } + + fmt.Printf("Node updated: %s\n", args[0]) + return nil + }, +} + +var nodeFetchTemplatesCmd = &cobra.Command{ + Use: "fetch-patch-templates", + Short: "Fetch patch templates from directory", + Long: `Copy latest patch templates from directory/setup/cluster-nodes/patch.templates to instance. + +This command is automatically called by 'apply' if templates are missing. +You can use it manually to update templates.`, + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + _, err = apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/nodes/fetch-templates", inst), nil) + if err != nil { + return err + } + + fmt.Println("Templates fetched successfully") + return nil + }, +} + +var nodeDeleteCmd = &cobra.Command{ + Use: "delete ", + Short: "Delete a node", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + _, err = apiClient.Delete(fmt.Sprintf("/api/v1/instances/%s/nodes/%s", inst, args[0])) + if err != nil { + return err + } + + fmt.Printf("Node deleted: %s\n", args[0]) + return nil + }, +} + +func init() { + nodeCmd.AddCommand(nodeDiscoverCmd) + nodeCmd.AddCommand(nodeDetectCmd) + nodeCmd.AddCommand(nodeListCmd) + nodeCmd.AddCommand(nodeShowCmd) + nodeCmd.AddCommand(nodeAddCmd) + nodeCmd.AddCommand(nodeApplyCmd) + nodeCmd.AddCommand(nodeUpdateCmd) + nodeCmd.AddCommand(nodeFetchTemplatesCmd) + nodeCmd.AddCommand(nodeDeleteCmd) + + // Add flags to node add command + nodeAddCmd.Flags().String("target-ip", "", "Target IP address for production") + nodeAddCmd.Flags().String("current-ip", "", "Current IP address (for maintenance mode)") + nodeAddCmd.Flags().String("disk", "", "Disk device (required, e.g., /dev/sda)") + nodeAddCmd.Flags().String("interface", "", "Network interface (optional, e.g., eth0)") + nodeAddCmd.Flags().String("schematic-id", "", "Talos schematic ID (optional, uses instance default)") + nodeAddCmd.Flags().Bool("maintenance", false, "Mark node as in maintenance mode") + + // Add flags to node update command + nodeUpdateCmd.Flags().String("target-ip", "", "Update target IP address") + nodeUpdateCmd.Flags().String("current-ip", "", "Update current IP address") + nodeUpdateCmd.Flags().String("disk", "", "Update disk device") + nodeUpdateCmd.Flags().String("interface", "", "Update network interface") + nodeUpdateCmd.Flags().String("schematic-id", "", "Update Talos schematic ID") + nodeUpdateCmd.Flags().Bool("maintenance", false, "Set maintenance mode") + nodeUpdateCmd.Flags().Bool("no-maintenance", false, "Clear maintenance mode") +} + diff --git a/cmd/operation.go b/cmd/operation.go new file mode 100644 index 0000000..2a246ed --- /dev/null +++ b/cmd/operation.go @@ -0,0 +1,142 @@ +package cmd + +import ( + "fmt" + "time" + + "github.com/r3labs/sse/v2" + "github.com/spf13/cobra" + + "github.com/wild-cloud/wild-central/wild/internal/config" +) + +// Operation commands +var operationCmd = &cobra.Command{ + Use: "operation", + Short: "Manage operations", +} + +var operationGetCmd = &cobra.Command{ + Use: "get ", + Short: "Get operation status", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/operations/%s?instance=%s", args[0], inst)) + if err != nil { + return err + } + + if outputFormat == "json" { + return printJSON(resp.Data) + } + + return printYAML(resp.Data) + }, +} + +var operationListCmd = &cobra.Command{ + Use: "list", + Short: "List operations", + RunE: func(cmd *cobra.Command, args []string) error { + resp, err := apiClient.Get("/api/v1/operations") + if err != nil { + return err + } + + if outputFormat == "json" { + return printJSON(resp.Data) + } + + ops := resp.GetArray("operations") + if len(ops) == 0 { + fmt.Println("No operations found") + return nil + } + + fmt.Printf("%-10s %-12s %-12s %-10s\n", "ID", "TYPE", "STATUS", "PROGRESS") + fmt.Println("--------------------------------------------------------") + for _, op := range ops { + if m, ok := op.(map[string]interface{}); ok { + fmt.Printf("%-10s %-12s %-12s %d%%\n", + m["id"], m["type"], m["status"], int(m["progress"].(float64))) + } + } + return nil + }, +} + +func init() { + operationCmd.AddCommand(operationGetCmd) + operationCmd.AddCommand(operationListCmd) +} + +// streamOperationOutput streams operation output via SSE +func streamOperationOutput(opID string) error { + // Get instance name + inst, err := getInstanceName() + if err != nil { + return err + } + + // Get base URL + baseURL := daemonURL + if baseURL == "" { + baseURL = config.GetDaemonURL() + } + + // Connect to SSE stream + url := fmt.Sprintf("%s/api/v1/operations/%s/stream?instance=%s", baseURL, opID, inst) + client := sse.NewClient(url) + events := make(chan *sse.Event) + + err = client.SubscribeChan("messages", events) + if err != nil { + return fmt.Errorf("failed to subscribe to SSE: %w", err) + } + + // Poll for completion in background + done := make(chan bool, 1) + go func() { + ticker := time.NewTicker(500 * time.Millisecond) + defer ticker.Stop() + for range ticker.C { + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/operations/%s?instance=%s", opID, inst)) + if err == nil { + status := resp.GetString("status") + if status == "completed" || status == "failed" { + time.Sleep(500 * time.Millisecond) // Give SSE time to flush + done <- true + return + } + } + } + }() + + // Stream events + for { + select { + case msg, ok := <-events: + if !ok { + // Channel closed + return nil + } + if msg != nil { + // Check for completion event + if string(msg.Event) == "complete" { + return nil + } + // Print data with newline + if msg.Data != nil { + fmt.Println(string(msg.Data)) + } + } + case <-done: + return nil + } + } +} diff --git a/cmd/pxe.go b/cmd/pxe.go new file mode 100644 index 0000000..a47644a --- /dev/null +++ b/cmd/pxe.go @@ -0,0 +1,78 @@ +package cmd + +import ( + "fmt" + + "github.com/spf13/cobra" +) + +// PXE commands +var pxeCmd = &cobra.Command{ + Use: "pxe", + Short: "Manage PXE assets", +} + +var pxeListCmd = &cobra.Command{ + Use: "list", + Short: "List PXE assets", + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/pxe/assets", inst)) + if err != nil { + return err + } + + if outputFormat == "json" { + return printJSON(resp.Data) + } + + assets := resp.GetArray("assets") + if len(assets) == 0 { + fmt.Println("No PXE assets found") + return nil + } + + fmt.Printf("%-20s %-15s %-12s\n", "NAME", "VERSION", "STATUS") + fmt.Println("--------------------------------------------------") + for _, asset := range assets { + if m, ok := asset.(map[string]interface{}); ok { + fmt.Printf("%-20s %-15s %-12s\n", + m["name"], m["version"], m["status"]) + } + } + return nil + }, +} + +var pxeDownloadCmd = &cobra.Command{ + Use: "download ", + Short: "Download PXE asset", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + resp, err := apiClient.Post(fmt.Sprintf("/api/v1/instances/%s/pxe/assets/%s/download", inst, args[0]), nil) + if err != nil { + return err + } + + fmt.Printf("Download started for: %s\n", args[0]) + if opID := resp.GetString("operation_id"); opID != "" { + fmt.Printf("Operation ID: %s\n", opID) + } + return nil + }, +} + +func init() { + pxeCmd.AddCommand(pxeListCmd) + pxeCmd.AddCommand(pxeDownloadCmd) +} + diff --git a/cmd/root.go b/cmd/root.go new file mode 100644 index 0000000..948e701 --- /dev/null +++ b/cmd/root.go @@ -0,0 +1,132 @@ +package cmd + +import ( + "encoding/json" + "fmt" + "os" + + "github.com/spf13/cobra" + "gopkg.in/yaml.v3" + + "github.com/wild-cloud/wild-central/wild/internal/client" + "github.com/wild-cloud/wild-central/wild/internal/config" +) + +var ( + apiClient *client.Client + + // Global flags + daemonURL string + instanceName string + outputFormat string +) + +// rootCmd represents the base command +var rootCmd = &cobra.Command{ + Use: "wild", + Short: "Wild Cloud CLI", + Long: `wild-cli is the command-line interface for Wild Central. + +It provides a simple way to manage Wild Cloud instances, nodes, clusters, +services, and applications through the Wild Central daemon.`, + PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + // Skip for commands that don't need API client + if cmd.Name() == "version" || cmd.Name() == "help" { + return nil + } + + // Get daemon URL: flag > env > default + url := daemonURL + if url == "" { + url = config.GetDaemonURL() + } + + // Create API client + apiClient = client.NewClient(url) + + return nil + }, +} + +// Execute runs the root command +func Execute() { + if err := rootCmd.Execute(); err != nil { + os.Exit(1) + } +} + +func init() { + // Global flags + rootCmd.PersistentFlags().StringVar(&daemonURL, "daemon-url", "", "Daemon URL (default: $WILD_DAEMON_URL or http://localhost:5055)") + rootCmd.PersistentFlags().StringVar(&instanceName, "instance", "", "Instance name (overrides current instance)") + rootCmd.PersistentFlags().StringVarP(&outputFormat, "output", "o", "text", "Output format (text, json, yaml)") + + // Add subcommands + rootCmd.AddCommand(versionCmd) + rootCmd.AddCommand(daemonCmd) + rootCmd.AddCommand(instanceCmd) + rootCmd.AddCommand(configCmd) + rootCmd.AddCommand(secretCmd) + rootCmd.AddCommand(nodeCmd) + rootCmd.AddCommand(pxeCmd) + rootCmd.AddCommand(clusterCmd) + rootCmd.AddCommand(serviceCmd) + rootCmd.AddCommand(appCmd) + rootCmd.AddCommand(backupCmd) + rootCmd.AddCommand(restoreCmd) + rootCmd.AddCommand(healthCmd) + rootCmd.AddCommand(dashboardCmd) + rootCmd.AddCommand(nodeIPCmd) + rootCmd.AddCommand(operationCmd) +} + +// getInstanceName returns the current instance name using the priority cascade +func getInstanceName() (string, error) { + // Create instance lister adapter for API client + var lister config.InstanceLister + if apiClient != nil { + lister = &instanceListerAdapter{client: apiClient} + } + + instance, _, err := config.GetCurrentInstance(instanceName, lister) + return instance, err +} + +// instanceListerAdapter adapts the API client to the InstanceLister interface +type instanceListerAdapter struct { + client *client.Client +} + +func (a *instanceListerAdapter) ListInstances() ([]string, error) { + resp, err := a.client.Get("/api/v1/instances") + if err != nil { + return nil, err + } + + instances := resp.GetArray("instances") + result := make([]string, 0, len(instances)) + for _, inst := range instances { + if name, ok := inst.(string); ok { + result = append(result, name) + } + } + + return result, nil +} + +// printJSON prints data as JSON +func printJSON(data interface{}) error { + encoder := json.NewEncoder(os.Stdout) + encoder.SetIndent("", " ") + return encoder.Encode(data) +} + +// printYAML prints data as YAML +func printYAML(data interface{}) error { + yamlData, err := yaml.Marshal(data) + if err != nil { + return err + } + fmt.Println(string(yamlData)) + return nil +} diff --git a/cmd/secret.go b/cmd/secret.go new file mode 100644 index 0000000..e26529d --- /dev/null +++ b/cmd/secret.go @@ -0,0 +1,72 @@ +package cmd + +import ( + "fmt" + + "github.com/spf13/cobra" + + "github.com/wild-cloud/wild-central/wild/internal/config" +) + +// Secret commands +var secretCmd = &cobra.Command{ + Use: "secret", + Short: "Manage secrets", +} + +var secretGetCmd = &cobra.Command{ + Use: "get ", + Short: "Get secret value (redacted)", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + key := args[0] + + // Request raw secrets (not redacted) + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/secrets?raw=true", inst)) + if err != nil { + return err + } + + // Secrets are returned directly at top level, not nested under "secrets" key + // Use nested path lookup for dot notation (e.g., cloudflare.token) + val := config.GetValue(resp.Data, key) + if val != nil { + fmt.Println(val) + } else { + return fmt.Errorf("secret '%s' not found", key) + } + return nil + }, +} + +var secretSetCmd = &cobra.Command{ + Use: "set ", + Short: "Set secret value", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + key, value := args[0], args[1] + + _, err = apiClient.Put(fmt.Sprintf("/api/v1/instances/%s/secrets", inst), map[string]string{ + key: value, + }) + if err != nil { + return err + } + + fmt.Printf("Secret updated: %s\n", key) + return nil + }, +} + +func init() { + secretCmd.AddCommand(secretGetCmd) + secretCmd.AddCommand(secretSetCmd) +} diff --git a/cmd/service.go b/cmd/service.go new file mode 100644 index 0000000..49b4dfe --- /dev/null +++ b/cmd/service.go @@ -0,0 +1,325 @@ +package cmd + +import ( + "fmt" + + "github.com/spf13/cobra" + + "github.com/wild-cloud/wild-central/wild/internal/config" + "github.com/wild-cloud/wild-central/wild/internal/prompt" +) + +// Service commands +var serviceCmd = &cobra.Command{ + Use: "service", + Short: "Manage services", +} + +var serviceListCmd = &cobra.Command{ + Use: "list", + Short: "List services", + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/services", inst)) + if err != nil { + return err + } + + if outputFormat == "json" { + return printJSON(resp.Data) + } + + services := resp.GetArray("services") + if len(services) == 0 { + fmt.Println("No services found") + return nil + } + + fmt.Printf("%-20s %-12s\n", "NAME", "STATUS") + fmt.Println("----------------------------------") + for _, svc := range services { + if m, ok := svc.(map[string]interface{}); ok { + fmt.Printf("%-20s %-12s\n", m["name"], m["status"]) + } + } + return nil + }, +} + +// ServiceManifest matches the daemon's ServiceManifest structure +type ServiceManifest struct { + Name string `json:"name"` + Description string `json:"description"` + Namespace string `json:"namespace"` + ConfigReferences []string `json:"configReferences"` + ServiceConfig map[string]ConfigDefinition `json:"serviceConfig"` +} + +// ConfigDefinition defines config that should be prompted during service setup +type ConfigDefinition struct { + Path string `json:"path"` + Prompt string `json:"prompt"` + Default string `json:"default"` + Type string `json:"type"` +} + +// ConfigUpdate represents a single configuration update +type ConfigUpdate struct { + Path string `json:"path"` + Value interface{} `json:"value"` +} + +var ( + fetchFlag bool + noDeployFlag bool +) + +var serviceInstallCmd = &cobra.Command{ + Use: "install ", + Short: "Install a service with interactive configuration", + Long: `Install and configure a cluster service. + +This command orchestrates the complete service installation lifecycle: + 1. Fetch service files from Wild Cloud Directory (if needed or --fetch) + 2. Validate configuration requirements + 3. Prompt for any missing service configuration + 4. Update instance configuration + 5. Compile templates using gomplate + 6. Deploy service to cluster (unless --no-deploy) + +Examples: + # Configure and deploy (most common) + wild service install metallb + + # Fetch fresh templates and deploy + wild service install metallb --fetch + + # Configure only, skip deployment + wild service install metallb --no-deploy + + # Fetch fresh templates, configure only + wild service install metallb --fetch --no-deploy + + # Use cached templates (default if files exist) + wild service install traefik +`, + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + serviceName := args[0] + + inst, err := getInstanceName() + if err != nil { + return err + } + + fmt.Printf("Installing service: %s\n", serviceName) + + // Step 1: Fetch service manifest + fmt.Println("\nFetching service manifest...") + manifestResp, err := apiClient.Get(fmt.Sprintf("/api/v1/services/%s/manifest", serviceName)) + if err != nil { + return fmt.Errorf("failed to fetch manifest: %w", err) + } + + // Parse manifest + var manifest ServiceManifest + manifestData := manifestResp.Data + // API returns camelCase field names + if name, ok := manifestData["name"].(string); ok { + manifest.Name = name + } + if desc, ok := manifestData["description"].(string); ok { + manifest.Description = desc + } + if namespace, ok := manifestData["namespace"].(string); ok { + manifest.Namespace = namespace + } + if refs, ok := manifestData["configReferences"].([]interface{}); ok { + manifest.ConfigReferences = make([]string, len(refs)) + for i, ref := range refs { + if s, ok := ref.(string); ok { + manifest.ConfigReferences[i] = s + } + } + } + if svcConfig, ok := manifestData["serviceConfig"].(map[string]interface{}); ok { + manifest.ServiceConfig = make(map[string]ConfigDefinition) + for key, val := range svcConfig { + if cfgMap, ok := val.(map[string]interface{}); ok { + cfg := ConfigDefinition{} + if path, ok := cfgMap["path"].(string); ok { + cfg.Path = path + } + if prompt, ok := cfgMap["prompt"].(string); ok { + cfg.Prompt = prompt + } + if def, ok := cfgMap["default"].(string); ok { + cfg.Default = def + } + if typ, ok := cfgMap["type"].(string); ok { + cfg.Type = typ + } + manifest.ServiceConfig[key] = cfg + } + } + } + + fmt.Printf("Service: %s - %s\n", manifest.Name, manifest.Description) + + // Step 2: Fetch current config + fmt.Println("\nFetching instance configuration...") + configResp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/config", inst)) + if err != nil { + return fmt.Errorf("failed to fetch config: %w", err) + } + + instanceConfig := configResp.Data + + // Step 3: Validate configReferences + if len(manifest.ConfigReferences) > 0 { + fmt.Println("\nValidating configuration references...") + missingPaths := config.ValidatePaths(instanceConfig, manifest.ConfigReferences) + if len(missingPaths) > 0 { + fmt.Println("\nERROR: Missing required configuration values:") + for _, path := range missingPaths { + fmt.Printf(" - %s\n", path) + } + fmt.Println("\nPlease set these configuration values before installing this service.") + fmt.Printf("Use: wild config set \n") + return fmt.Errorf("missing required configuration") + } + fmt.Println("All required configuration references are present.") + } + + // Step 4: Process serviceConfig - prompt for missing values + var updates []ConfigUpdate + + if len(manifest.ServiceConfig) > 0 { + fmt.Println("\nConfiguring service parameters...") + + for key, cfg := range manifest.ServiceConfig { + // Check if path already set + existingValue := config.GetValue(instanceConfig, cfg.Path) + if existingValue != nil && existingValue != "" && existingValue != "null" { + fmt.Printf(" %s: %v (already set)\n", cfg.Path, existingValue) + continue + } + + // Expand default template + defaultValue := cfg.Default + if defaultValue != "" { + expanded, err := config.ExpandTemplate(defaultValue, instanceConfig) + if err != nil { + return fmt.Errorf("failed to expand template for %s: %w", key, err) + } + defaultValue = expanded + } + + // Prompt user + var value string + switch cfg.Type { + case "int": + intVal, err := prompt.Int(cfg.Prompt, 0) + if err != nil { + return fmt.Errorf("failed to read input for %s: %w", key, err) + } + value = fmt.Sprintf("%d", intVal) + case "bool": + boolVal, err := prompt.Bool(cfg.Prompt, false) + if err != nil { + return fmt.Errorf("failed to read input for %s: %w", key, err) + } + if boolVal { + value = "true" + } else { + value = "false" + } + default: // string + var err error + value, err = prompt.String(cfg.Prompt, defaultValue) + if err != nil { + return fmt.Errorf("failed to read input for %s: %w", key, err) + } + } + + // Add to updates + updates = append(updates, ConfigUpdate{ + Path: cfg.Path, + Value: value, + }) + + fmt.Printf(" %s: %s\n", cfg.Path, value) + } + } + + // Step 5: Update configuration if needed + if len(updates) > 0 { + fmt.Println("\nUpdating instance configuration...") + _, err = apiClient.Patch( + fmt.Sprintf("/api/v1/instances/%s/config", inst), + map[string]interface{}{ + "updates": updates, + }, + ) + if err != nil { + return fmt.Errorf("failed to update configuration: %w", err) + } + fmt.Printf("Configuration updated (%d values)\n", len(updates)) + } + + // Step 6: Install service with lifecycle control + if noDeployFlag { + fmt.Println("\nConfiguring service...") + } else { + fmt.Println("\nInstalling service...") + } + + installResp, err := apiClient.Post( + fmt.Sprintf("/api/v1/instances/%s/services", inst), + map[string]interface{}{ + "name": serviceName, + "fetch": fetchFlag, + "deploy": !noDeployFlag, + }, + ) + if err != nil { + return fmt.Errorf("failed to install service: %w", err) + } + + // Show appropriate success message + if noDeployFlag { + fmt.Printf("\nāœ“ Service configured: %s\n", serviceName) + fmt.Printf(" Templates compiled and ready to deploy\n") + fmt.Printf(" To deploy later, run: wild service install %s\n", serviceName) + } else { + // Stream installation output + opID := installResp.GetString("operation_id") + if opID != "" { + fmt.Printf("Installing service: %s\n\n", serviceName) + if err := streamOperationOutput(opID); err != nil { + // If streaming fails, show operation ID for manual monitoring + fmt.Printf("\nCouldn't stream output: %v\n", err) + fmt.Printf("Operation ID: %s\n", opID) + fmt.Printf("Monitor with: wild operation get %s\n", opID) + } else { + fmt.Printf("\nāœ“ Service installed successfully: %s\n", serviceName) + } + } + } + + return nil + }, +} + +func init() { + serviceInstallCmd.Flags().BoolVar(&fetchFlag, "fetch", false, "Fetch fresh templates from directory before installing") + serviceInstallCmd.Flags().BoolVar(&noDeployFlag, "no-deploy", false, "Configure and compile only, skip deployment") + + serviceCmd.AddCommand(serviceListCmd) + serviceCmd.AddCommand(serviceInstallCmd) +} + diff --git a/cmd/utility.go b/cmd/utility.go new file mode 100644 index 0000000..ab4f47e --- /dev/null +++ b/cmd/utility.go @@ -0,0 +1,68 @@ +package cmd + +import ( + "fmt" + + "github.com/spf13/cobra" +) + +// Utility commands +var healthCmd = &cobra.Command{ + Use: "health", + Short: "Check cluster health", + RunE: func(cmd *cobra.Command, args []string) error { + inst, err := getInstanceName() + if err != nil { + return err + } + + resp, err := apiClient.Get(fmt.Sprintf("/api/v1/instances/%s/utilities/health", inst)) + if err != nil { + return err + } + + if outputFormat == "json" { + return printJSON(resp.Data) + } + + return printYAML(resp.Data) + }, +} + +var dashboardCmd = &cobra.Command{ + Use: "dashboard", + Short: "Dashboard operations", +} + +var dashboardTokenCmd = &cobra.Command{ + Use: "token", + Short: "Get dashboard token", + RunE: func(cmd *cobra.Command, args []string) error { + resp, err := apiClient.Get("/api/v1/utilities/dashboard/token") + if err != nil { + return err + } + + fmt.Println(resp.GetString("token")) + return nil + }, +} + +func init() { + dashboardCmd.AddCommand(dashboardTokenCmd) +} + +var nodeIPCmd = &cobra.Command{ + Use: "node-ip", + Short: "Get control plane IP", + RunE: func(cmd *cobra.Command, args []string) error { + resp, err := apiClient.Get("/api/v1/utilities/controlplane/ip") + if err != nil { + return err + } + + fmt.Println(resp.GetString("ip")) + return nil + }, +} + diff --git a/cmd/version.go b/cmd/version.go new file mode 100644 index 0000000..eabec61 --- /dev/null +++ b/cmd/version.go @@ -0,0 +1,38 @@ +package cmd + +import ( + "fmt" + + "github.com/spf13/cobra" +) + +var ( + // Version information set during build + Version = "dev" + GitCommit = "unknown" + BuildTime = "unknown" +) + +var versionCmd = &cobra.Command{ + Use: "version", + Short: "Show version information", + Long: `Display version information for the CLI and optionally for the cluster.`, + Run: func(cmd *cobra.Command, args []string) { + fmt.Printf("wild-cli version: %s\n", Version) + fmt.Printf("Git commit: %s\n", GitCommit) + fmt.Printf("Build time: %s\n", BuildTime) + + // If connected to daemon, show cluster versions + if apiClient != nil { + resp, err := apiClient.Get("/api/v1/utilities/version") + if err == nil { + if k8s, ok := resp.Data["kubernetes"].(string); ok { + fmt.Printf("Kubernetes: %s\n", k8s) + } + if talos, ok := resp.Data["talos"].(string); ok && talos != "" { + fmt.Printf("Talos: %s\n", talos) + } + } + } + }, +} diff --git a/docs/setup.md b/docs/setup.md new file mode 100644 index 0000000..ed9a50d --- /dev/null +++ b/docs/setup.md @@ -0,0 +1,143 @@ +# Wild Central CLI Setup Guide + +This guide shows how to set up a complete Wild Cloud cluster using the `wild` CLI. + +All configuration values are examples. + +## Prerequisites + +```bash +# Ensure wild daemon is running +wild daemon status + +# Create and select your instance +wild instance create test-cloud +wild instance use test-cloud +``` + +## 1. Cluster Configuration + +Configure your cluster's basic settings: + +```bash +# Set operator email +wild config set operator.email "your-email@example.com" + +wild config set cloud.baseDomain "payne.io" +wild config set cloud.domain "cloud2.payne.io" +wild config set cloud.internalDomain "internal.cloud2.payne.io" + +# Set cluster name +wild config set cluster.name "wild-cluster" + +# Configure network settings +wild config set cloud.router.ip "192.168.8.1" +wild config set cloud.dns.ip "192.168.8.50" +wild config set cloud.dhcpRange "192.168.8.34,192.168.8.79" +wild config set cloud.dnsmasq.interface "eth0" + +# Configure MetalLB IP pool +wild config set cluster.ipAddressPool "192.168.8.80-192.168.8.89" +wild config set cluster.loadBalancerIp "192.168.8.80" + +# Configure control plane VIP +wild config set cluster.nodes.control.vip "192.168.8.30" + +# Set Talos version and schematic +wild config set cluster.nodes.talos.version "v1.11.2" +wild config set cluster.nodes.talos.schematicId "434a0300db532066f1098e05ac068159371d00f0aba0a3103a0e826e83825c82" +``` + +## 2. Generate Cluster Configuration + +```bash +wild cluster config generate +``` + +## 3. Configure talosctl Context + +```bash +wild cluster talosconfig --persist +source <(wild instance env) +``` + +Set up three control plane nodes for high availability: + +```bash +# Control plane node 1 +wild node detect 192.168.8.122 +wild node add test-control-1 controlplane --current-ip 192.168.8.122 --target-ip 192.168.8.31 --disk /dev/sdb --interface enp4s0 +wild node apply test-control-1 +``` + +After the first control plane node is up, bootstrap the cluster! + +```bash +wild cluster bootstrap test-control-1 +wild cluster kubeconfig --persist +source <(wild instance env) +``` + +Now repeat the detect/add/apply for control nodes 2 and 3. + +After all control plane nodes are running, configure endpoints to use the VIP: + +```bash +wild cluster endpoints +``` + +This updates the talosconfig to use the control plane VIP and retrieves the kubeconfig. + +### Worker Nodes + +Add as many worker nodes as you would like: + +```bash +wild node detect 192.168.8.100 +wild node add test-worker-1 worker --target-ip 192.168.8.100 --disk /dev/sda --interface eth0 --maintenance +wild node apply test-worker-1 +``` + +## 5. Services Setup + +Install cluster services in dependency order: + +```bash +wild service install metallb +wild service install longhorn +wild service install traefik +wild service install coredns +wild service install node-feature-discovery + +wild config set certManager.cloudflare.domain "payne.io" +wild config set certManager.cloudflare.zoneId "" +wild secret set cloudflare.token "" +wild service install cert-manager + +wild service install externaldns +wild service install kubernetes-dashboard +wild service install nfs +wild service install docker-registry +wild service install nvidia-device-plugin +wild service install smtp +``` + +**Or install all services at once:** + +```bash +wild services install --all +``` + +## 6. Verification + +Verify your cluster is healthy: + +```bash +# Check cluster health +wild health + +# Check nodes +kubectl get nodes + +# Get dashboard token +wild dashboard token diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..6b4ffd2 --- /dev/null +++ b/go.mod @@ -0,0 +1,28 @@ +module github.com/wild-cloud/wild-central/wild + +go 1.24 + +require ( + github.com/spf13/cobra v1.10.1 + github.com/spf13/viper v1.21.0 + gopkg.in/yaml.v3 v3.0.1 +) + +require ( + github.com/fsnotify/fsnotify v1.9.0 // indirect + github.com/go-viper/mapstructure/v2 v2.4.0 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/pelletier/go-toml/v2 v2.2.4 // indirect + github.com/r3labs/sse/v2 v2.10.0 // indirect + github.com/sagikazarmark/locafero v0.11.0 // indirect + github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect + github.com/spf13/afero v1.15.0 // indirect + github.com/spf13/cast v1.10.0 // indirect + github.com/spf13/pflag v1.0.10 // indirect + github.com/subosito/gotenv v1.6.0 // indirect + go.yaml.in/yaml/v3 v3.0.4 // indirect + golang.org/x/net v0.0.0-20191116160921-f9c825593386 // indirect + golang.org/x/sys v0.29.0 // indirect + golang.org/x/text v0.28.0 // indirect + gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..b559cb8 --- /dev/null +++ b/go.sum @@ -0,0 +1,67 @@ +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= +github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= +github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/r3labs/sse/v2 v2.10.0 h1:hFEkLLFY4LDifoHdiCN/LlGBAdVJYsANaLqNYa1l/v0= +github.com/r3labs/sse/v2 v2.10.0/go.mod h1:Igau6Whc+F17QUgML1fYe1VPZzTV6EMCnYktEmkNJ7I= +github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= +github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik= +github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw= +github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U= +github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= +github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= +github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= +github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= +github.com/spf13/cobra v1.10.1 h1:lJeBwCfmrnXthfAupyUTzJ/J4Nc1RsHC/mSRU2dll/s= +github.com/spf13/cobra v1.10.1/go.mod h1:7SmJGaTHFVBY0jW4NXGluQoLvhqFQM+6XSKD+P4XaB0= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= +github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= +github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= +github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= +go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/net v0.0.0-20191116160921-f9c825593386 h1:ktbWvQrW08Txdxno1PiDpSxPXG6ndGsfnJjRRtkM0LQ= +golang.org/x/net v0.0.0-20191116160921-f9c825593386/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU= +golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng= +golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU= +gopkg.in/cenkalti/backoff.v1 v1.1.0 h1:Arh75ttbsvlpVA7WtVpH4u9h6Zl46xuptxqLxPiSo4Y= +gopkg.in/cenkalti/backoff.v1 v1.1.0/go.mod h1:J6Vskwqd+OMVJl8C33mmtxTBs2gyzfv7UDAkHu8BrjI= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/install-man-page.sh b/install-man-page.sh new file mode 100755 index 0000000..82715ec --- /dev/null +++ b/install-man-page.sh @@ -0,0 +1,14 @@ +#!/bin/sh + +my_path="$(command -v yq)" + +if [ -z "$my_path" ]; then + echo "'yq' wasn't found in your PATH, so we don't know where to put the man pages." + echo "Please update your PATH to include yq, and run this script again." + exit 1 +fi + +# ex: ~/.local/bin/yq => ~/.local/ +my_prefix="$(dirname "$(dirname "$(command -v yq)")")" +mkdir -p "$my_prefix/share/man/man1/" +cp yq.1 "$my_prefix/share/man/man1/" diff --git a/internal/client/client.go b/internal/client/client.go new file mode 100644 index 0000000..367ee28 --- /dev/null +++ b/internal/client/client.go @@ -0,0 +1,152 @@ +// Package client provides HTTP client for Wild Central daemon API +package client + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "time" +) + +// Client is the HTTP client for the Wild Central daemon +type Client struct { + baseURL string + httpClient *http.Client +} + +// NewClient creates a new API client +func NewClient(baseURL string) *Client { + return &Client{ + baseURL: baseURL, + httpClient: &http.Client{ + Timeout: 30 * time.Second, + }, + } +} + +// APIResponse is the API response format +type APIResponse struct { + Data map[string]interface{} + Error string `json:"error,omitempty"` +} + +// Get makes a GET request to the API +func (c *Client) Get(path string) (*APIResponse, error) { + return c.doRequest("GET", path, nil) +} + +// Post makes a POST request to the API +func (c *Client) Post(path string, body interface{}) (*APIResponse, error) { + return c.doRequest("POST", path, body) +} + +// Put makes a PUT request to the API +func (c *Client) Put(path string, body interface{}) (*APIResponse, error) { + return c.doRequest("PUT", path, body) +} + +// Delete makes a DELETE request to the API +func (c *Client) Delete(path string) (*APIResponse, error) { + return c.doRequest("DELETE", path, nil) +} + +// Patch makes a PATCH request to the API +func (c *Client) Patch(path string, body interface{}) (*APIResponse, error) { + return c.doRequest("PATCH", path, body) +} + +// doRequest performs the actual HTTP request +func (c *Client) doRequest(method, path string, body interface{}) (*APIResponse, error) { + url := c.baseURL + path + + var reqBody io.Reader + if body != nil { + jsonData, err := json.Marshal(body) + if err != nil { + return nil, fmt.Errorf("failed to marshal request body: %w", err) + } + reqBody = bytes.NewBuffer(jsonData) + } + + req, err := http.NewRequest(method, url, reqBody) + if err != nil { + return nil, fmt.Errorf("failed to create request: %w", err) + } + + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + + resp, err := c.httpClient.Do(req) + if err != nil { + return nil, fmt.Errorf("request failed: %w", err) + } + defer resp.Body.Close() + + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read response: %w", err) + } + + // Check for HTTP error status + if resp.StatusCode >= 400 { + // Try to parse error response + var errResp map[string]interface{} + if err := json.Unmarshal(respBody, &errResp); err == nil { + if errMsg, ok := errResp["error"].(string); ok { + return nil, fmt.Errorf("API error: %s", errMsg) + } + } + return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(respBody)) + } + + // Parse response data directly (daemon doesn't wrap in "data" field) + var data map[string]interface{} + if err := json.Unmarshal(respBody, &data); err != nil { + return nil, fmt.Errorf("failed to parse response: %w\nResponse: %s", err, string(respBody)) + } + + return &APIResponse{Data: data}, nil +} + +// GetData extracts data from API response +func (r *APIResponse) GetData(key string) interface{} { + if r.Data == nil { + return nil + } + return r.Data[key] +} + +// GetString extracts string data from API response +func (r *APIResponse) GetString(key string) string { + val := r.GetData(key) + if str, ok := val.(string); ok { + return str + } + return "" +} + +// GetMap extracts map data from API response +func (r *APIResponse) GetMap(key string) map[string]interface{} { + val := r.GetData(key) + if m, ok := val.(map[string]interface{}); ok { + return m + } + return nil +} + +// GetArray extracts array data from API response +func (r *APIResponse) GetArray(key string) []interface{} { + val := r.GetData(key) + if arr, ok := val.([]interface{}); ok { + return arr + } + return nil +} + +// BaseURL returns the base URL of the client +func (c *Client) BaseURL() string { + return c.baseURL +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..1112c42 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,17 @@ +// Package config handles CLI configuration +package config + +import ( + "os" +) + +// GetDaemonURL returns the daemon URL from environment or default +func GetDaemonURL() string { + // Check environment variable first + if url := os.Getenv("WILD_DAEMON_URL"); url != "" { + return url + } + + // Use default matching daemon's port + return "http://localhost:5055" +} diff --git a/internal/config/example_test.go b/internal/config/example_test.go new file mode 100644 index 0000000..86c435a --- /dev/null +++ b/internal/config/example_test.go @@ -0,0 +1,44 @@ +package config_test + +import ( + "fmt" + + "github.com/wild-cloud/wild-central/wild/internal/config" +) + +func ExampleGetValue() { + cfg := map[string]interface{}{ + "cloud": map[string]interface{}{ + "domain": "example.com", + }, + } + + value := config.GetValue(cfg, "cloud.domain") + fmt.Println(value) + // Output: example.com +} + +func ExampleValidatePaths() { + cfg := map[string]interface{}{ + "cloud": map[string]interface{}{ + "domain": "example.com", + }, + } + + required := []string{"cloud.domain", "cloud.name", "network.subnet"} + missing := config.ValidatePaths(cfg, required) + fmt.Printf("Missing paths: %v\n", missing) + // Output: Missing paths: [cloud.name network.subnet] +} + +func ExampleExpandTemplate() { + cfg := map[string]interface{}{ + "cloud": map[string]interface{}{ + "domain": "example.com", + }, + } + + result, _ := config.ExpandTemplate("registry.{{ .cloud.domain }}", cfg) + fmt.Println(result) + // Output: registry.example.com +} diff --git a/internal/config/instance.go b/internal/config/instance.go new file mode 100644 index 0000000..07a44ab --- /dev/null +++ b/internal/config/instance.go @@ -0,0 +1,83 @@ +package config + +import ( + "fmt" + "os" + "path/filepath" + "strings" +) + +// GetWildCLIDataDir returns the Wild CLI data directory +func GetWildCLIDataDir() string { + if dir := os.Getenv("WILD_CLI_DATA"); dir != "" { + return dir + } + home, err := os.UserHomeDir() + if err != nil { + return ".wildcloud" + } + return filepath.Join(home, ".wildcloud") +} + +// GetCurrentInstance resolves the current instance using the priority cascade: +// 1. --instance flag (passed as parameter) +// 2. $WILD_CLI_DATA/current_instance file +// 3. Auto-select first instance from API +func GetCurrentInstance(flagInstance string, apiClient InstanceLister) (string, string, error) { + // Priority 1: --instance flag + if flagInstance != "" { + return flagInstance, "flag", nil + } + + // Priority 2: current_instance file + dataDir := GetWildCLIDataDir() + currentFile := filepath.Join(dataDir, "current_instance") + + if data, err := os.ReadFile(currentFile); err == nil { + instance := strings.TrimSpace(string(data)) + if instance != "" { + return instance, "file", nil + } + } + + // Priority 3: Auto-select first instance from API + if apiClient != nil { + instances, err := apiClient.ListInstances() + if err != nil { + return "", "", fmt.Errorf("no instance configured and failed to list instances: %w", err) + } + + if len(instances) == 0 { + return "", "", fmt.Errorf("no instance configured and no instances available (create one with: wild instance create )") + } + + // Auto-select first instance + return instances[0], "auto", nil + } + + return "", "", fmt.Errorf("no instance configured (use --instance flag or run: wild instance use )") +} + +// SetCurrentInstance persists the instance selection to file +func SetCurrentInstance(instance string) error { + dataDir := GetWildCLIDataDir() + + // Create directory if it doesn't exist + if err := os.MkdirAll(dataDir, 0755); err != nil { + return fmt.Errorf("failed to create data directory: %w", err) + } + + currentFile := filepath.Join(dataDir, "current_instance") + + // Write instance name to file + if err := os.WriteFile(currentFile, []byte(instance), 0644); err != nil { + return fmt.Errorf("failed to write current instance file: %w", err) + } + + return nil +} + +// InstanceLister is an interface for listing instances (allows for testing and dependency injection) +type InstanceLister interface { + ListInstances() ([]string, error) +} diff --git a/internal/config/instance_test.go b/internal/config/instance_test.go new file mode 100644 index 0000000..3910267 --- /dev/null +++ b/internal/config/instance_test.go @@ -0,0 +1,210 @@ +package config + +import ( + "os" + "path/filepath" + "testing" +) + +// mockInstanceLister is a mock implementation of InstanceLister for testing +type mockInstanceLister struct { + instances []string + err error +} + +func (m *mockInstanceLister) ListInstances() ([]string, error) { + if m.err != nil { + return nil, m.err + } + return m.instances, nil +} + +func TestGetCurrentInstance(t *testing.T) { + // Save and restore env var + oldWildCLIData := os.Getenv("WILD_CLI_DATA") + defer os.Setenv("WILD_CLI_DATA", oldWildCLIData) + + // Create temp directory for testing + tmpDir := t.TempDir() + os.Setenv("WILD_CLI_DATA", tmpDir) + + tests := []struct { + name string + flagInstance string + fileInstance string + apiInstances []string + wantInstance string + wantSource string + wantErr bool + }{ + { + name: "flag takes priority", + flagInstance: "flag-instance", + fileInstance: "file-instance", + apiInstances: []string{"api-instance"}, + wantInstance: "flag-instance", + wantSource: "flag", + wantErr: false, + }, + { + name: "file takes priority over api", + flagInstance: "", + fileInstance: "file-instance", + apiInstances: []string{"api-instance"}, + wantInstance: "file-instance", + wantSource: "file", + wantErr: false, + }, + { + name: "auto-select first from api", + flagInstance: "", + fileInstance: "", + apiInstances: []string{"first-instance", "second-instance"}, + wantInstance: "first-instance", + wantSource: "auto", + wantErr: false, + }, + { + name: "no instance available", + flagInstance: "", + fileInstance: "", + apiInstances: []string{}, + wantInstance: "", + wantSource: "", + wantErr: true, + }, + { + name: "no api client and no config", + flagInstance: "", + fileInstance: "", + apiInstances: nil, + wantInstance: "", + wantSource: "", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Set up file + currentFile := filepath.Join(tmpDir, "current_instance") + if tt.fileInstance != "" { + if err := os.WriteFile(currentFile, []byte(tt.fileInstance), 0644); err != nil { + t.Fatalf("Failed to write test file: %v", err) + } + } else { + os.Remove(currentFile) + } + + // Set up API client mock + var lister InstanceLister + if tt.apiInstances != nil { + lister = &mockInstanceLister{instances: tt.apiInstances} + } + + // Test + gotInstance, gotSource, err := GetCurrentInstance(tt.flagInstance, lister) + + if (err != nil) != tt.wantErr { + t.Errorf("GetCurrentInstance() error = %v, wantErr %v", err, tt.wantErr) + return + } + + if gotInstance != tt.wantInstance { + t.Errorf("GetCurrentInstance() instance = %v, want %v", gotInstance, tt.wantInstance) + } + + if gotSource != tt.wantSource { + t.Errorf("GetCurrentInstance() source = %v, want %v", gotSource, tt.wantSource) + } + }) + } +} + +func TestSetCurrentInstance(t *testing.T) { + // Save and restore env var + oldWildCLIData := os.Getenv("WILD_CLI_DATA") + defer os.Setenv("WILD_CLI_DATA", oldWildCLIData) + + // Create temp directory for testing + tmpDir := t.TempDir() + os.Setenv("WILD_CLI_DATA", tmpDir) + + // Test setting instance + testInstance := "test-instance" + err := SetCurrentInstance(testInstance) + if err != nil { + t.Fatalf("SetCurrentInstance() error = %v", err) + } + + // Verify file was written + currentFile := filepath.Join(tmpDir, "current_instance") + data, err := os.ReadFile(currentFile) + if err != nil { + t.Fatalf("Failed to read current_instance file: %v", err) + } + + if string(data) != testInstance { + t.Errorf("File content = %v, want %v", string(data), testInstance) + } + + // Test updating instance + newInstance := "new-instance" + err = SetCurrentInstance(newInstance) + if err != nil { + t.Fatalf("SetCurrentInstance() error = %v", err) + } + + data, err = os.ReadFile(currentFile) + if err != nil { + t.Fatalf("Failed to read current_instance file: %v", err) + } + + if string(data) != newInstance { + t.Errorf("File content = %v, want %v", string(data), newInstance) + } +} + +func TestGetWildCLIDataDir(t *testing.T) { + // Save and restore env var + oldWildCLIData := os.Getenv("WILD_CLI_DATA") + defer os.Setenv("WILD_CLI_DATA", oldWildCLIData) + + tests := []struct { + name string + envVar string + wantDir string + }{ + { + name: "custom directory from env", + envVar: "/custom/path", + wantDir: "/custom/path", + }, + { + name: "default directory when env not set", + envVar: "", + // We can't predict the exact home directory, so we'll just check it's not empty + wantDir: "", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if tt.envVar != "" { + os.Setenv("WILD_CLI_DATA", tt.envVar) + } else { + os.Unsetenv("WILD_CLI_DATA") + } + + gotDir := GetWildCLIDataDir() + + if tt.wantDir != "" && gotDir != tt.wantDir { + t.Errorf("GetWildCLIDataDir() = %v, want %v", gotDir, tt.wantDir) + } + + if tt.wantDir == "" && gotDir == "" { + t.Errorf("GetWildCLIDataDir() should not be empty when using default") + } + }) + } +} diff --git a/internal/config/validator.go b/internal/config/validator.go new file mode 100644 index 0000000..4b80e89 --- /dev/null +++ b/internal/config/validator.go @@ -0,0 +1,61 @@ +package config + +import ( + "bytes" + "fmt" + "strings" + "text/template" +) + +// ValidatePaths checks if all required paths exist in the config +// Returns a list of missing paths +func ValidatePaths(config map[string]interface{}, paths []string) []string { + var missing []string + for _, path := range paths { + if GetValue(config, path) == nil { + missing = append(missing, path) + } + } + return missing +} + +// GetValue retrieves a nested value from config using dot notation +// Returns nil if the path doesn't exist +func GetValue(config map[string]interface{}, path string) interface{} { + parts := strings.Split(path, ".") + var current interface{} = config + + for _, part := range parts { + m, ok := current.(map[string]interface{}) + if !ok { + return nil + } + current = m[part] + if current == nil { + return nil + } + } + + return current +} + +// ExpandTemplate expands {{ .path.to.value }} templates in the string +// Returns the original string if no templates are present +func ExpandTemplate(tmpl string, config map[string]interface{}) (string, error) { + // Return original if no template markers + if !strings.Contains(tmpl, "{{") { + return tmpl, nil + } + + t, err := template.New("config").Parse(tmpl) + if err != nil { + return "", fmt.Errorf("parse template: %w", err) + } + + var buf bytes.Buffer + if err := t.Execute(&buf, config); err != nil { + return "", fmt.Errorf("execute template: %w", err) + } + + return buf.String(), nil +} diff --git a/internal/config/validator_test.go b/internal/config/validator_test.go new file mode 100644 index 0000000..37c58d6 --- /dev/null +++ b/internal/config/validator_test.go @@ -0,0 +1,153 @@ +package config + +import ( + "reflect" + "testing" +) + +func TestGetValue(t *testing.T) { + config := map[string]interface{}{ + "cloud": map[string]interface{}{ + "domain": "example.com", + "name": "test-cloud", + }, + "simple": "value", + } + + tests := []struct { + name string + path string + expected interface{} + }{ + {"simple path", "simple", "value"}, + {"nested path", "cloud.domain", "example.com"}, + {"nested path 2", "cloud.name", "test-cloud"}, + {"missing path", "missing", nil}, + {"missing nested", "cloud.missing", nil}, + {"invalid nested", "simple.nested", nil}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := GetValue(config, tt.path) + if !reflect.DeepEqual(result, tt.expected) { + t.Errorf("GetValue(%q) = %v, want %v", tt.path, result, tt.expected) + } + }) + } +} + +func TestValidatePaths(t *testing.T) { + config := map[string]interface{}{ + "cloud": map[string]interface{}{ + "domain": "example.com", + "name": "test-cloud", + }, + "network": map[string]interface{}{ + "subnet": "10.0.0.0/24", + }, + } + + tests := []struct { + name string + paths []string + expected []string + }{ + { + name: "all paths exist", + paths: []string{"cloud.domain", "cloud.name", "network.subnet"}, + expected: nil, + }, + { + name: "some paths missing", + paths: []string{"cloud.domain", "missing.path", "network.missing"}, + expected: []string{"missing.path", "network.missing"}, + }, + { + name: "all paths missing", + paths: []string{"foo.bar", "baz.qux"}, + expected: []string{"foo.bar", "baz.qux"}, + }, + { + name: "empty paths", + paths: []string{}, + expected: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := ValidatePaths(config, tt.paths) + if !reflect.DeepEqual(result, tt.expected) { + t.Errorf("ValidatePaths() = %v, want %v", result, tt.expected) + } + }) + } +} + +func TestExpandTemplate(t *testing.T) { + config := map[string]interface{}{ + "cloud": map[string]interface{}{ + "domain": "example.com", + "name": "test-cloud", + }, + "port": 8080, + } + + tests := []struct { + name string + template string + expected string + shouldErr bool + }{ + { + name: "simple template", + template: "registry.{{ .cloud.domain }}", + expected: "registry.example.com", + }, + { + name: "multiple templates", + template: "{{ .cloud.name }}.{{ .cloud.domain }}", + expected: "test-cloud.example.com", + }, + { + name: "no template", + template: "plain-string", + expected: "plain-string", + }, + { + name: "template with text", + template: "http://{{ .cloud.domain }}:{{ .port }}/api", + expected: "http://example.com:8080/api", + }, + { + name: "invalid template syntax", + template: "{{ .cloud.domain", + shouldErr: true, + }, + { + name: "missing value renders as no value", + template: "{{ .missing.path }}", + expected: "", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result, err := ExpandTemplate(tt.template, config) + if tt.shouldErr { + if err == nil { + t.Errorf("ExpandTemplate() expected error, got nil") + } + return + } + if err != nil { + t.Errorf("ExpandTemplate() unexpected error: %v", err) + return + } + if result != tt.expected { + t.Errorf("ExpandTemplate() = %q, want %q", result, tt.expected) + } + }) + } +} diff --git a/internal/prompt/example_test.go b/internal/prompt/example_test.go new file mode 100644 index 0000000..93ebe5f --- /dev/null +++ b/internal/prompt/example_test.go @@ -0,0 +1,73 @@ +package prompt_test + +import ( + "fmt" + // "github.com/wild-cloud/wild-central/wild/internal/prompt" +) + +// ExampleString demonstrates the String prompt function +func ExampleString() { + // This example shows the prompt output format + // Actual usage would read from stdin interactively + fmt.Println("Enter SMTP host [smtp.gmail.com]:") + // User input: (returns default) + // Result: "smtp.gmail.com" + + fmt.Println("Enter SMTP host [smtp.gmail.com]:") + // User input: "smtp.example.com" + // Result: "smtp.example.com" +} + +// ExampleInt demonstrates the Int prompt function +func ExampleInt() { + // This example shows the prompt output format + fmt.Println("Enter SMTP port [587]:") + // User input: (returns default) + // Result: 587 + + fmt.Println("Enter SMTP port [587]:") + // User input: "465" + // Result: 465 +} + +// ExampleBool demonstrates the Bool prompt function +func ExampleBool() { + // This example shows the prompt output format + fmt.Println("Enable TLS [Y/n]:") + // User input: (returns default true) + // Result: true + + fmt.Println("Enable TLS [Y/n]:") + // User input: "n" + // Result: false + + fmt.Println("Enable debug mode [y/N]:") + // User input: (returns default false) + // Result: false + + fmt.Println("Enable debug mode [y/N]:") + // User input: "yes" + // Result: true +} + +// Example usage in a real command +func ExampleUsage() { + // Example of using prompt functions in a CLI command: + // + // host, err := prompt.String("Enter SMTP host", "smtp.gmail.com") + // if err != nil { + // return err + // } + // + // port, err := prompt.Int("Enter SMTP port", 587) + // if err != nil { + // return err + // } + // + // useTLS, err := prompt.Bool("Enable TLS", true) + // if err != nil { + // return err + // } + // + // fmt.Printf("Configuration: host=%s, port=%d, tls=%v\n", host, port, useTLS) +} diff --git a/internal/prompt/prompt.go b/internal/prompt/prompt.go new file mode 100644 index 0000000..dba2a01 --- /dev/null +++ b/internal/prompt/prompt.go @@ -0,0 +1,89 @@ +// Package prompt provides simple utilities for interactive CLI prompts +package prompt + +import ( + "bufio" + "fmt" + "os" + "strconv" + "strings" +) + +// String prompts the user for a string value with a default +func String(prompt, defaultValue string) (string, error) { + if defaultValue != "" { + fmt.Printf("%s [%s]: ", prompt, defaultValue) + } else { + fmt.Printf("%s: ", prompt) + } + + reader := bufio.NewReader(os.Stdin) + input, err := reader.ReadString('\n') + if err != nil { + return "", fmt.Errorf("failed to read input: %w", err) + } + + input = strings.TrimSpace(input) + if input == "" { + return defaultValue, nil + } + + return input, nil +} + +// Int prompts the user for an integer value with a default +func Int(prompt string, defaultValue int) (int, error) { + fmt.Printf("%s [%d]: ", prompt, defaultValue) + + reader := bufio.NewReader(os.Stdin) + input, err := reader.ReadString('\n') + if err != nil { + return 0, fmt.Errorf("failed to read input: %w", err) + } + + input = strings.TrimSpace(input) + if input == "" { + return defaultValue, nil + } + + value, err := strconv.Atoi(input) + if err != nil { + return 0, fmt.Errorf("invalid integer value: %s", input) + } + + return value, nil +} + +// Bool prompts the user for a boolean value with a default +func Bool(prompt string, defaultValue bool) (bool, error) { + defaultStr := "y/n" + if defaultValue { + defaultStr = "Y/n" + } else { + defaultStr = "y/N" + } + + fmt.Printf("%s [%s]: ", prompt, defaultStr) + + reader := bufio.NewReader(os.Stdin) + input, err := reader.ReadString('\n') + if err != nil { + return false, fmt.Errorf("failed to read input: %w", err) + } + + input = strings.TrimSpace(input) + input = strings.ToLower(input) + + if input == "" { + return defaultValue, nil + } + + switch input { + case "y", "yes", "true": + return true, nil + case "n", "no", "false": + return false, nil + default: + return false, fmt.Errorf("invalid boolean value: %s (expected y/n/yes/no/true/false)", input) + } +} diff --git a/internal/prompt/prompt_test.go b/internal/prompt/prompt_test.go new file mode 100644 index 0000000..7b0ed11 --- /dev/null +++ b/internal/prompt/prompt_test.go @@ -0,0 +1,64 @@ +package prompt + +import ( + "testing" +) + +// Note: These are basic unit tests for the prompt package. +// Interactive testing requires manual verification since the functions +// read from stdin and write to stdout. + +func TestBoolParsing(t *testing.T) { + tests := []struct { + name string + input string + expected bool + hasError bool + }{ + {"yes", "yes", true, false}, + {"y", "y", true, false}, + {"true", "true", true, false}, + {"no", "no", false, false}, + {"n", "n", false, false}, + {"false", "false", false, false}, + {"invalid", "maybe", false, true}, + {"invalid", "xyz", false, true}, + } + + // Test the parsing logic that would be used by Bool function + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + input := tt.input + var result bool + var err error + + switch input { + case "y", "yes", "true": + result = true + case "n", "no", "false": + result = false + default: + err = &invalidBoolError{} + } + + if tt.hasError { + if err == nil { + t.Errorf("expected error for input %q, got nil", tt.input) + } + } else { + if err != nil { + t.Errorf("unexpected error for input %q: %v", tt.input, err) + } + if result != tt.expected { + t.Errorf("expected %v for input %q, got %v", tt.expected, tt.input, result) + } + } + }) + } +} + +type invalidBoolError struct{} + +func (e *invalidBoolError) Error() string { + return "invalid boolean value" +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..8d9c762 --- /dev/null +++ b/main.go @@ -0,0 +1,7 @@ +package main + +import "github.com/wild-cloud/wild-central/wild/cmd" + +func main() { + cmd.Execute() +}