├── .github └── workflows │ └── docker-image.yml ├── .gitignore ├── .readthedocs.yml ├── Dockerfile ├── Dockerfile-ubuntu ├── LICENSE ├── Makefile ├── README.md ├── cmd └── fetchit │ └── main.go ├── doc.go ├── docs ├── conf.py ├── index.rst ├── media │ ├── Harpoon.png │ └── Method.png ├── methods.rst ├── purpose.rst ├── quick_start.rst └── running.rst ├── examples ├── ansible.yaml ├── ansible │ └── playbook.yaml ├── ci-config.yaml ├── ci-filetransfer-config.yaml ├── clean-config.yaml ├── config-reload.yaml ├── config-url.yaml ├── filetransfer-config-single-file.yaml ├── filetransfer-config.yaml ├── filetransfer │ ├── anotherfile.txt │ └── hello.txt ├── full-suite-disconnected-usb.yaml ├── full-suite-disconnected.yaml ├── full-suite-with-skew.yaml ├── full-suite.yaml ├── gitsign-verify-config.yaml ├── glob-config.yaml ├── imageLoad-config.yaml ├── imageLoad │ └── byo-image.yaml ├── kube-play-config.yaml ├── kube │ ├── 1-pvc.yaml │ ├── 2-example.yaml │ └── 3-example.yaml ├── pat-testing-config.yaml ├── pat-testing-kube.yaml ├── podman-secret-raw-config.yaml ├── podman-secret-raw.yaml ├── raw-config.yaml ├── raw │ ├── cap.json │ ├── cap.yaml │ ├── color1.json │ └── color2.yaml ├── readme-config.yaml ├── single-raw │ └── welcome.yaml ├── ssh-config.yaml ├── systemd-autoupdate.yaml ├── systemd-config-single-file.yaml ├── systemd-config.yaml ├── systemd-enable-user.yaml ├── systemd-enable.yaml ├── systemd-restart.yaml └── systemd │ ├── httpd.service │ ├── podman-auto-update.service │ ├── podman-auto-update.timer │ └── podman-auto-update.timer.d-override.conf ├── go.mod ├── go.sum ├── method_containers ├── ansible │ ├── Dockerfile │ └── ansible.cfg └── systemd │ ├── Dockerfile-systemctl │ └── systemd-script ├── pkg └── engine │ ├── ansible.go │ ├── apply.go │ ├── clean.go │ ├── common.go │ ├── config.go │ ├── container.go │ ├── disconnected.go │ ├── fetchit.go │ ├── filetransfer.go │ ├── gitauth.go │ ├── image.go │ ├── kube.go │ ├── raw.go │ ├── start.go │ ├── systemd.go │ ├── types.go │ └── utils │ ├── errors.go │ ├── errors_test.go │ └── util.go ├── scripts └── entry.sh └── systemd ├── fetchit-root.service └── fetchit-user.service /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | __pycache__/ 3 | _build/ 4 | venv/ 5 | results/*.png 6 | results/*.txt 7 | processed_data/*.dat 8 | vendor 9 | _output 10 | fetchit 11 | !fetchit/ 12 | config.yaml 13 | *.env 14 | -------------------------------------------------------------------------------- /.readthedocs.yml: -------------------------------------------------------------------------------- 1 | # .readthedocs.yml 2 | # Read the Docs configuration file 3 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 4 | 5 | # Required 6 | version: 2 7 | 8 | # Build documentation in the docs/ directory with Sphinx 9 | sphinx: 10 | configuration: docs/conf.py 11 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # BUILD STAGE 2 | FROM registry.access.redhat.com/ubi8/go-toolset as builder 3 | 4 | ARG ARCH=amd64 5 | ARG MAKE_TARGET=cross-build-linux-$ARCH 6 | 7 | USER root 8 | 9 | LABEL name=fetchit-build 10 | 11 | ENV GOPATH=/opt/app-root GOCACHE=/mnt/cache GO111MODULE=on 12 | 13 | RUN dnf -y install gpgme-devel device-mapper-devel 14 | 15 | WORKDIR $GOPATH/src/github.com/containers/fetchit 16 | 17 | COPY . . 18 | 19 | RUN GOPATH=/opt/app-root GOCACHE=/mnt/cache make $MAKE_TARGET 20 | 21 | RUN mv $GOPATH/src/github.com/containers/fetchit/_output/bin/linux_$ARCH/fetchit /usr/local/bin/ 22 | 23 | RUN mv ./scripts/entry.sh /usr/local/bin/ 24 | 25 | # RUN STAGE 26 | FROM registry.access.redhat.com/ubi9/ubi-minimal:latest 27 | 28 | RUN microdnf -y install rsync device-mapper-libs && microdnf clean all 29 | 30 | COPY --from=builder /usr/local/bin/fetchit /usr/local/bin/ 31 | COPY --from=builder /usr/local/bin/entry.sh /usr/local/bin/ 32 | 33 | WORKDIR /opt 34 | 35 | CMD ["entry.sh"] 36 | -------------------------------------------------------------------------------- /Dockerfile-ubuntu: -------------------------------------------------------------------------------- 1 | FROM ubuntu:devel 2 | LABEL maintainer="brett.dellegrazie@gmail.com" 3 | 4 | ENV container=docker LANG=C.UTF-8 5 | 6 | # Enable all repositories 7 | RUN sed -i 's/# deb/deb/g' /etc/apt/sources.list 8 | 9 | RUN apt-get update && \ 10 | apt-get install --no-install-recommends -y \ 11 | git podman curl dbus systemd systemd-cron rsyslog iproute2 python-apt-doc python3-apt-dbg python3-apt python-apt-common sudo bash ca-certificates && \ 12 | apt-get clean && \ 13 | rm -rf /usr/share/doc/* /usr/share/man/* /var/lib/apt/lists/* /tmp/* /var/tmp/* 14 | 15 | RUN sed -i 's/^\(module(load="imklog")\)/#\1/' /etc/rsyslog.conf 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Export shell defined to support Ubuntu 2 | export SHELL := $(shell which bash) 3 | 4 | PROJECT_DIR := $(shell dirname $(abspath $(lastword $(MAKEFILE_LIST)))) 5 | 6 | # Include openshift build-machinery-go libraries 7 | include ./vendor/github.com/openshift/build-machinery-go/make/golang.mk 8 | 9 | SRC_ROOT :=$(shell pwd) 10 | 11 | OUTPUT_DIR :=_output 12 | CROSS_BUILD_BINDIR :=$(OUTPUT_DIR)/bin 13 | CTR_CMD :=$(or $(shell which podman 2>/dev/null), $(shell which docker 2>/dev/null)) 14 | ARCH := $(shell uname -m |sed -e "s/x86_64/amd64/" |sed -e "s/aarch64/arm64/") 15 | 16 | # restrict included verify-* targets to only process project files 17 | GO_PACKAGES=$(go list ./cmd/... ./pkg/engine/...) 18 | 19 | GO_LD_FLAGS := $(GC_FLAGS) -ldflags "-X k8s.io/component-base/version.gitMajor=0 \ 20 | -X k8s.io/component-base/version.gitMajor=0 \ 21 | -X k8s.io/component-base/version.gitMinor=0 \ 22 | -X k8s.io/component-base/version.gitVersion=v0.0.0 \ 23 | -X k8s.io/component-base/version.gitTreeState=clean \ 24 | -X k8s.io/client-go/pkg/version.gitMajor=0 \ 25 | -X k8s.io/client-go/pkg/version.gitMinor=0 \ 26 | -X k8s.io/client-go/pkg/version.gitVersion=v0.0.0 \ 27 | -X k8s.io/client-go/pkg/version.gitTreeState=clean \ 28 | $(LD_FLAGS)" 29 | 30 | # These tags make sure we can statically link and avoid shared dependencies 31 | GO_BUILD_FLAGS :=-tags 'include_gcs include_oss containers_image_openpgp gssapi providerless netgo osusergo exclude_graphdriver_btrfs' 32 | 33 | # targets "all:" and "build:" defined in vendor/github.com/openshift/build-machinery-go/make/targets/golang/build.mk 34 | fetchit: build-containerized-cross-build-linux-amd64 35 | .PHONY: fetchit 36 | 37 | 38 | OS := $(shell go env GOOS) 39 | ARCH := $(shell go env GOARCH) 40 | 41 | ############################### 42 | # host build targets # 43 | ############################### 44 | 45 | _build_local: 46 | @mkdir -p "$(CROSS_BUILD_BINDIR)/$(GOOS)_$(GOARCH)" 47 | +@GOOS=$(GOOS) GOARCH=$(GOARCH) $(MAKE) --no-print-directory build \ 48 | GO_BUILD_PACKAGES:=./cmd/fetchit \ 49 | GO_BUILD_BINDIR:=$(CROSS_BUILD_BINDIR)/$(GOOS)_$(GOARCH) 50 | 51 | cross-build-linux-amd64: 52 | +$(MAKE) _build_local GOOS=linux GOARCH=amd64 53 | .PHONY: cross-build-linux-amd64 54 | 55 | cross-build-linux-arm64: 56 | +$(MAKE) _build_local GOOS=linux GOARCH=arm64 57 | .PHONY: cross-build-linux-arm64 58 | 59 | cross-build: cross-build-linux-amd64 cross-build-linux-arm64 60 | .PHONY: cross-build 61 | 62 | ############################### 63 | # containerized build targets # 64 | ############################### 65 | _build_containerized_amd: 66 | @if [ -z '$(CTR_CMD)' ] ; then echo '!! ERROR: containerized builds require podman||docker CLI, none found $$PATH' >&2 && exit 1; fi 67 | $(CTR_CMD) build . --file Dockerfile --tag quay.io/fetchit/fetchit-amd:latest \ 68 | --build-arg ARCH=amd64 \ 69 | --build-arg MAKE_TARGET="cross-build-linux-amd64" \ 70 | --platform="linux/amd64" 71 | 72 | .PHONY: _build_containerized_amd 73 | 74 | _build_containerized_arm: 75 | @if [ -z '$(CTR_CMD)' ] ; then echo '!! ERROR: containerized builds require podman||docker CLI, none found $$PATH' >&2 && exit 1; fi 76 | $(CTR_CMD) build . --file Dockerfile --tag quay.io/fetchit/fetchit-arm:latest \ 77 | --build-arg ARCH=arm64 \ 78 | --build-arg MAKE_TARGET="cross-build-linux-arm64" \ 79 | --platform="linux/arm64" 80 | 81 | .PHONY: _build_containerized_arm 82 | 83 | build-containerized-cross-build-linux-amd64: 84 | +$(MAKE) _build_containerized_amd ARCH=amd64 85 | .PHONY: build-containerized-cross-build-linux-amd64 86 | 87 | build-containerized-cross-build-linux-arm64: 88 | +$(MAKE) _build_containerized_arm ARCH=arm64 89 | .PHONY: build-containerized-cross-build-linux-arm64 90 | 91 | build-containerized-cross-build: 92 | +$(MAKE) build-containerized-cross-build-linux-amd64 93 | +$(MAKE) build-containerized-cross-build-linux-arm64 94 | .PHONY: build-containerized-cross-build 95 | 96 | ############################### 97 | # ansible targets # 98 | ############################### 99 | _build_ansible_amd: 100 | @if [ -z '$(CTR_CMD)' ] ; then echo '!! ERROR: containerized builds require podman||docker CLI, none found $$PATH' >&2 && exit 1; fi 101 | $(CTR_CMD) build -f method_containers/ansible/Dockerfile --tag quay.io/fetchit/fetchit-ansible-amd:latest \ 102 | --build-arg ARCH="amd64" \ 103 | --build-arg MAKE_TARGET="cross-build-linux-amd64" \ 104 | --platform="linux/amd64" 105 | 106 | .PHONY: _build_ansible_amd 107 | 108 | _build_ansible_arm: 109 | @if [ -z '$(CTR_CMD)' ] ; then echo '!! ERROR: containerized builds require podman||docker CLI, none found $$PATH' >&2 && exit 1; fi 110 | $(CTR_CMD) build -f method_containers/ansible/Dockerfile --tag quay.io/fetchit/fetchit-ansible-arm:latest \ 111 | --build-arg ARCH="arm64" \ 112 | --build-arg MAKE_TARGET="cross-build-linux-arm64" \ 113 | --platform="linux/arm64" 114 | 115 | .PHONY: _build_ansible_arm 116 | 117 | build-ansible-cross-build-linux-amd64: 118 | +$(MAKE) _build_ansible_amd ARCH=amd64 119 | .PHONY: build-ansible-cross-build-linux-amd64 120 | 121 | build-ansible-cross-build-linux-arm64: 122 | +$(MAKE) _build_ansible_arm ARCH=arm64 123 | .PHONY: build-ansible-cross-build-linux-arm64 124 | 125 | build-ansible-cross-build: 126 | +$(MAKE) build-ansible-cross-build-linux-amd64 127 | +$(MAKE) build-ansbile-cross-build-linux-arm64 128 | .PHONY: build-ansible-cross-build 129 | 130 | ############################### 131 | # systemd targets # 132 | ############################### 133 | 134 | systemd: build-systemd-cross-build-linux-amd64 135 | .PHONY: systemd 136 | 137 | _build_systemd_amd: 138 | @if [ -z '$(CTR_CMD)' ] ; then echo '!! ERROR: containerized builds require podman||docker CLI, none found $$PATH' >&2 && exit 1; fi 139 | $(CTR_CMD) build . --file method_containers/systemd/Dockerfile-systemctl --tag quay.io/fetchit/fetchit-systemd-amd:latest \ 140 | --platform="linux/amd64" 141 | 142 | .PHONY: _build_systemd_amd 143 | 144 | _build_systemd_arm: 145 | @if [ -z '$(CTR_CMD)' ] ; then echo '!! ERROR: containerized builds require podman||docker CLI, none found $$PATH' >&2 && exit 1; fi 146 | $(CTR_CMD) build . --file method_containers/systemd/Dockerfile-systemctl --tag quay.io/fetchit/fetchit-systemd-arm:latest \ 147 | --platform="linux/arm64" 148 | 149 | .PHONY: _build_systemd_arm 150 | 151 | build-systemd-cross-build-linux-amd64: 152 | +$(MAKE) _build_systemd_amd 153 | .PHONY: build-systemd-cross-build-linux-amd64 154 | 155 | build-systemd-cross-build-linux-arm64: 156 | +$(MAKE) _build_systemd_arm 157 | .PHONY: build-systemd-cross-build-linux-arm64 158 | 159 | build-systemd-cross-build: 160 | +$(MAKE) build-systemd-cross-build-linux-amd64 161 | +$(MAKE) build-systemd-cross-build-linux-arm64 162 | .PHONY: build-systemd-cross-build 163 | 164 | ############################### 165 | # dev targets # 166 | ############################### 167 | 168 | clean-cross-build: 169 | $(RM) -r '$(CROSS_BUILD_BINDIR)' 170 | $(RM) -rf $(OUTPUT_DIR)/staging 171 | if [ -d '$(OUTPUT_DIR)' ]; then rmdir --ignore-fail-on-non-empty '$(OUTPUT_DIR)'; fi 172 | .PHONY: clean-cross-build 173 | 174 | clean: clean-cross-build 175 | .PHONY: clean 176 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Fetchit 2 | The purpose of FetchIt is to allow for GitOps management of podman managed containers. 3 | 4 | This project is currently under development. For a more detailed explanation of the project visit the docs page. 5 | https://fetchit.readthedocs.io/ 6 | 7 | A quickstart example is available at https://github.com/containers/fetchit/blob/main/docs/quick_start.rst 8 | 9 | ## Developing 10 | To develop and test changes of FetchIt, the FetchIt image can be built locally and then run on the development system. 11 | 12 | ``` 13 | go mod tidy 14 | go mod vendor 15 | podman build . --file Dockerfile --tag quay.io/fetchit/fetchit-amd:latest 16 | podman tag quay.io/fetchit/fetchit-amd:latest quay.io/fetchit/fetchit:latest 17 | ``` 18 | 19 | Once the image has been successfully built the image can be ran using the following command. 20 | 21 | ``` 22 | 23 | podman run -d --rm --name fetchit --security-opt label=disable -v fetchit-volume:/opt -v ./examples/readme-config.yaml:/opt/config.yaml -v /run/user/$(id -u)/podman//podman.sock:/run/podman/podman.sock quay.io/fetchit/fetchit:latest 24 | ``` 25 | 26 | ## Running 27 | FetchIt requires the podman socket to be running on the host. The socket can be enabled for a specific user or for root. 28 | 29 | To enable the socket for $USER: 30 | 31 | ``` 32 | systemctl --user enable podman.socket --now 33 | ``` 34 | 35 | To enable the socket for root: 36 | 37 | ``` 38 | systemctl enable podman.socket --now 39 | ``` 40 | 41 | 42 | #### Verify running containers before deploying fetchit. 43 | 44 | ``` 45 | podman ps 46 | 47 | CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 48 | ``` 49 | 50 | 51 | ### FetchIt launch options 52 | FetchIt and can be started manually or launched via systemd. 53 | 54 | Define the parameters in your `$HOME/.fetchit/config.yaml` to relate to your git repository. 55 | This example can be found in [./examples/readme-config.yaml](examples/readme-config.yaml) 56 | 57 | ``` 58 | targetConfigs: 59 | - url: https://github.com/containers/fetchit 60 | branch: main 61 | fileTransfer: 62 | - name: ft-ex 63 | targetPath: examples/fileTransfer 64 | destinationDirectory: /tmp 65 | schedule: "*/1 * * * *" 66 | raw: 67 | - name: raw-ex 68 | targetPath: examples/raw 69 | schedule: "*/1 * * * *" 70 | ``` 71 | 72 | #### Launch using systemd 73 | Two systemd files are provided to allow for FetchIt to run as a user or as root. The files are under the systemd folder, differentiated by fetchit-root and fetchit-user. 74 | 75 | Ensure that there is a config at `$HOME/.fetchit/config.yaml` before attempting to start the service. 76 | 77 | For root 78 | ``` 79 | cp systemd/fetchit-root.service /etc/systemd/system/fetchit.service 80 | systemctl enable fetchit --now 81 | ``` 82 | 83 | For $USER 84 | ``` 85 | mkdir -p ~/.config/systemd/user/ 86 | cp systemd/fetchit-user.service ~/.config/systemd/user/fetchit.service 87 | systemctl --user enable fetchit --now 88 | ``` 89 | 90 | #### Manually launch the fetchit container using a podman volume 91 | 92 | ``` 93 | podman run -d --rm --name fetchit \ 94 | -v fetchit-volume:/opt \ 95 | -v $HOME/.fetchit:/opt/mount \ 96 | -v /run/user/$(id -u)/podman//podman.sock:/run/podman/podman.sock \ 97 | --security-opt label=disable \ 98 | quay.io/fetchit/fetchit:latest 99 | ``` 100 | 101 | **NOTE:** 102 | * If a podman volume is not the preferred storage solution a directory can be used as well. 103 | An example would be `-v ~/fetchit-volume:/opt` instead of `-v fetchit-volume:/opt`. 104 | * For filetransfer, the `destination directory must exist` on the host. 105 | 106 | The container will be started and will run in the background. To view the logs: 107 | 108 | ``` 109 | podman logs -f fetchit 110 | 111 | git clone https://github.com/containers/fetchit main --recursive 112 | Creating podman container from ./fetchit/examples/raw/example.json 113 | Trying to pull docker.io/mmumshad/simple-webapp-color:latest... 114 | Getting image source signatures 115 | Copying blob sha256:b023afffd10b07f646968c0f1405ac7b611feca6da6fbc2bb8c55f2492bdde07 116 | Copying blob sha256:d4eee24d4dacb41c21411e0477a741655303cdc48b18a948632c31f0f3a70bb8 117 | Copying blob sha256:1607093a898cc241de8712e4361dcd907898fff35b945adca42db3963f3827b3 118 | Copying blob sha256:b59856e9f0abefedc34fcefc3f57c4955cc384785663745532ddc31a89641c83 119 | Copying blob sha256:55cbf04beb7001d222c71bfdeae780bda19d5cb37b8dbd65ff0d3e6a0b9b74e6 120 | Copying blob sha256:13e2e806d7c88f357958d798c097b4fc0cd6e3aea888ad7e584fba5a0e7d3ec9 121 | Copying blob sha256:e90bc178f0458c231d8e355756f9f0f51e22a4e6c5ff8c9c6cb8e48d2c158000 122 | Copying blob sha256:bd415728f75acd3ee7699f4bb31dfa8c39a935d5a6acea4b580568cd730100a9 123 | Copying blob sha256:06d08c7638af6fc0c05f9c7e5ec43ae7b24ca72bbfaba4d065578358ed38ab15 124 | Copying blob sha256:98b4690dc1c724ec64b18475f1be8d37e10c058788da16aa2e4ca7260c1aac68 125 | Copying blob sha256:3a4e7915e2111a1546b662863d4192f98283e53a66ac34296d90823563d12040 126 | Copying blob sha256:b2567acc3f180ce1113a668c5950e8123b493c5b85e8e51651310ee21799c67d 127 | Copying blob sha256:9a8ea045c9261c180a34df19cfc9bb3c3f28f29b279bf964ee801536e8244f2f 128 | Copying config sha256:96bb69733441c4a81ec77348208198aba7a5a78f4dc22429e7a56b25f63d2b73 129 | Writing manifest to image destination 130 | Storing signatures 131 | A container named colors already exists. Removing the container before redeploy. 132 | Container created. 133 | time="2022-02-15T18:04:14Z" level=info msg="Going to start container \"53d86851aad9fc362cb61493c495ec262217c1759e061724dc1f974c35d93d5b\"" 134 | Container started....Requeuing 135 | ``` 136 | 137 | #### Verify the sample applications are running 138 | 139 | ``` 140 | podman ps 141 | 142 | CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 143 | edefaf7c3139 quay.io/fetchit/fetchit:latest /usr/local/bin/fe... 25 seconds ago Up 26 seconds ago fetchit 144 | 508106ff37c1 docker.io/mmumshad/simple-webapp-color:latest python ./app.py 25 seconds ago Up 25 seconds ago 0.0.0.0:7070->8080/tcp cap1 145 | 90556a8725db docker.io/mmumshad/simple-webapp-color:latest python ./app.py 24 seconds ago Up 25 seconds ago 0.0.0.0:9090->8080/tcp cap2 146 | 8ce0f010231a docker.io/mmumshad/simple-webapp-color:latest python ./app.py 24 seconds ago Up 25 seconds ago 0.0.0.0:8080->8080/tcp colors1 147 | be95a69686e8 docker.io/mmumshad/simple-webapp-color:latest python ./app.py 24 seconds ago Up 25 seconds ago 0.0.0.0:9080->8080/tcp colors2 148 | ``` 149 | 150 | Also, view applications at `localhost:8080` and `localhost:9080` 151 | 152 | #### Verify the file is placed on the host 153 | 154 | ``` 155 | watch ls -al /tmp/hello.txt 156 | ``` 157 | 158 | #### Clean up 159 | 160 | ``` 161 | podman stop colors1 colors2 fetchit && podman rm colors1 colors2 && podman volume rm fetchit-volume 162 | ``` 163 | -------------------------------------------------------------------------------- /cmd/fetchit/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "github.com/containers/fetchit/pkg/engine" 4 | 5 | func main() { 6 | engine.Execute() 7 | } 8 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | package fetchit_doc 2 | 3 | import ( 4 | _ "github.com/openshift/build-machinery-go" 5 | ) 6 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # FetchIt documentation build configuration file, created by 5 | # sphinx-quickstart on Fri Jun 8 14:27:52 2018. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | # 20 | import os 21 | import sys 22 | 23 | 24 | # -- General configuration ------------------------------------------------ 25 | 26 | # If your documentation needs a minimal Sphinx version, state it here. 27 | # 28 | # needs_sphinx = '1.0' 29 | 30 | # Add any Sphinx extension module names here, as strings. They can be 31 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 32 | # ones. 33 | extensions = [ 34 | 'sphinx.ext.autodoc', 35 | 'sphinx.ext.autosectionlabel', 36 | ] 37 | 38 | # Add any paths that contain templates here, relative to this directory. 39 | templates_path = ['_templates'] 40 | 41 | # The suffix(es) of source filenames. 42 | # You can specify multiple suffix as a list of string: 43 | # 44 | # source_suffix = ['.rst', '.md'] 45 | source_suffix = '.rst' 46 | 47 | # The master toctree document. 48 | master_doc = 'index' 49 | 50 | # General information about the project. 51 | project = 'FetchIt' 52 | copyright = '2018, Harsha' 53 | author = 'Harsha' 54 | 55 | # The version info for the project you're documenting, acts as replacement for 56 | # |version| and |release|, also used in various other places throughout the 57 | # built documents. 58 | # 59 | # The short X.Y version. 60 | version = '0.1' 61 | # The full version, including alpha/beta/rc tags. 62 | release = '0.1' 63 | 64 | # The language for content autogenerated by Sphinx. Refer to documentation 65 | # for a list of supported languages. 66 | # 67 | # This is also used if you do content translation via gettext catalogs. 68 | # Usually you set "language" from the command line for these cases. 69 | language = None 70 | 71 | # List of patterns, relative to source directory, that match files and 72 | # directories to ignore when looking for source files. 73 | # This patterns also effect to html_static_path and html_extra_path 74 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 75 | 76 | # The name of the Pygments (syntax highlighting) style to use. 77 | pygments_style = 'sphinx' 78 | 79 | # If true, `todo` and `todoList` produce output, else they produce nothing. 80 | todo_include_todos = False 81 | 82 | 83 | # -- Options for HTML output ---------------------------------------------- 84 | 85 | # The theme to use for HTML and HTML Help pages. See the documentation for 86 | # a list of builtin themes. 87 | # 88 | html_theme = 'sphinx_rtd_theme' 89 | 90 | # Theme options are theme-specific and customize the look and feel of a theme 91 | # further. For a list of options available for each theme, see the 92 | # documentation. 93 | # 94 | # html_theme_options = {} 95 | 96 | # Add any paths that contain custom static files (such as style sheets) here, 97 | # relative to this directory. They are copied after the builtin static files, 98 | # so a file named "default.css" will overwrite the builtin "default.css". 99 | html_static_path = [] 100 | 101 | # Custom sidebar templates, must be a dictionary that maps document names 102 | # to template names. 103 | # 104 | # This is required for the alabaster theme 105 | # refs: https://alabaster.readthedocs.io/en/latest/installation.html#sidebars 106 | html_sidebars = { 107 | '**': [ 108 | 'relations.html', # needs 'show_related': True theme option to display 109 | 'searchbox.html', 110 | ] 111 | } 112 | 113 | 114 | # -- Options for HTMLHelp output ------------------------------------------ 115 | 116 | # Output file base name for HTML help builder. 117 | htmlhelp_basename = 'FetchItdoc' 118 | 119 | 120 | # -- Options for LaTeX output --------------------------------------------- 121 | 122 | latex_elements = { 123 | # The paper size ('letterpaper' or 'a4paper'). 124 | # 125 | # 'papersize': 'letterpaper', 126 | 127 | # The font size ('10pt', '11pt' or '12pt'). 128 | # 129 | # 'pointsize': '10pt', 130 | 131 | # Additional stuff for the LaTeX preamble. 132 | # 133 | # 'preamble': '', 134 | 135 | # Latex figure (float) alignment 136 | # 137 | # 'figure_align': 'htbp', 138 | } 139 | 140 | # Grouping the document tree into LaTeX files. List of tuples 141 | # (source start file, target name, title, 142 | # author, documentclass [howto, manual, or own class]). 143 | latex_documents = [ 144 | (master_doc, 'FetchIt.tex', 'FetchIt Documentation', 145 | 'Harsha', 'manual'), 146 | ] 147 | 148 | 149 | # -- Options for manual page output --------------------------------------- 150 | 151 | # One entry per manual page. List of tuples 152 | # (source start file, name, description, authors, manual section). 153 | man_pages = [ 154 | (master_doc, 'fetchit', 'FetchIt Documentation', 155 | [author], 1) 156 | ] 157 | 158 | 159 | # -- Options for Texinfo output ------------------------------------------- 160 | 161 | # Grouping the document tree into Texinfo files. List of tuples 162 | # (source start file, target name, title, author, 163 | # dir menu entry, description, category) 164 | texinfo_documents = [ 165 | (master_doc, 'FetchIt', 'FetchIt Documentation', 166 | author, 'FetchIt', 'GitOps engine for Podman', 167 | 'Miscellaneous'), 168 | ] 169 | 170 | 171 | 172 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. this is a comment, it is not rendered 2 | when adding new *.rst files, reference them here 3 | in this index.rst for them to be rendered and added to the 4 | table of contents 5 | 6 | 7 | FetchIt 8 | ======= 9 | FetchIt was designed to allow for the hands off management of containers running on system running podman. Check out the :ref:`Quick Start` for a quick example of FetchIt. 10 | 11 | .. toctree:: 12 | quick_start 13 | purpose 14 | methods 15 | running -------------------------------------------------------------------------------- /docs/media/Harpoon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/containers/fetchit/6cb83288db688c678e7329ea6b5beae3f5e72732/docs/media/Harpoon.png -------------------------------------------------------------------------------- /docs/media/Method.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/containers/fetchit/6cb83288db688c678e7329ea6b5beae3f5e72732/docs/media/Method.png -------------------------------------------------------------------------------- /docs/methods.rst: -------------------------------------------------------------------------------- 1 | Configuration 2 | ============= 3 | The YAML configuration file defines git targets and the methods to use, how frequently to check the repository, 4 | and various configuration values that relate to that method. 5 | 6 | A target is a unique value that holds methods. Mutiple git targets (targetConfigs) can be defined. Methods that can be configured 7 | include `Raw`, `Systemd`, `Kube`, `Ansible`, `FileTransfer`, `Prune`, and `ConfigReload`. 8 | 9 | Examples of all methods are located in the `FetchIt repository `_ 10 | 11 | Dynamic Configuration Reload 12 | ---------------------------- 13 | 14 | There are a few ways currently to trigger FetchIt to reload its targets without requiring a restart. The first is to 15 | pass the environment variable `$FETCHIT_CONFIG_URL` to the `podman run` command running the FetchIt image. 16 | The second is to include a ConfigReload. If neither of these exist, a restart of the FetchIt 17 | pod is required to reload targetConfigs. The following fields are required with the ConfigReload method: 18 | 19 | .. code-block:: yaml 20 | 21 | configReload: 22 | schedule: "*/5 * * * *" 23 | configUrl: https://raw.githubusercontent.com/containers/fetchit/main/examples/config-reload.yaml 24 | 25 | Changes pushed to the ConfigURL will trigger a reloading of FetchIt target configs. It's recommended to include the ConfigReload 26 | in the FetchIt config to enable updates to target configs without requiring a restart. 27 | 28 | The configuration above will pull in the file from the repository and reload the FetchIt config. 29 | The YAML above demonstrates the minimal required objects to start FetchIt. Once FetchIt is running, the full configuration file 30 | that is stored in git will be used. 31 | 32 | Dynamic Configuration Reload Using a Private Registry 33 | ----------------------------------------------------- 34 | 35 | The ConfigReload method can be used to reload target configs from a private registry but this comes with the warning to ensure that 36 | the repository is not public. The config.yaml will need to include the credentials to access the private registry. 37 | 38 | When using a GitHub PAT token, the config.yaml will need to include the following fields: 39 | 40 | .. code-block:: yaml 41 | 42 | configReload: 43 | schedule: "*/5 * * * *" 44 | pat: github-alphanumeric-token 45 | configUrl: https://raw.githubusercontent.com/containers/fetchit/main/examples/config-reload.yaml 46 | 47 | When using basic authentication the config.yaml will need to include the following fields: 48 | 49 | .. code-block:: yaml 50 | 51 | gitAuth: 52 | username: bob 53 | password: bobpassword 54 | configReload: 55 | schedule: "*/5 * * * *" 56 | configUrl: https://raw.githubusercontent.com/containers/fetchit/main/examples/config-reload.yaml 57 | 58 | NOTE: This is not recommended for public repositories. As your credentials will need to be in clear text in the config.yaml. 59 | 60 | PAT is the preferred method of authentication when available as the credentials can be reissued or locked. The PAT will be used both for the configuration file and the repo 61 | 62 | .. code-block:: yaml 63 | 64 | gitAuth: 65 | pat: github-alphanumeric-token 66 | configReload: 67 | schedule: "*/5 * * * *" 68 | configUrl: https://raw.githubusercontent.com/containers/fetchit/main/examples/config-reload.yaml 69 | 70 | 71 | Configuring FetchIt Using Environment Variables 72 | ----------------------------------------------- 73 | 74 | FetchIt can also be configured by providing the FetchIt config through the `FETCHIT_CONFIG` environment variable. 75 | This approach will use the contents of `FETCHIT_CONFIG` to configure the FetchIt application. 76 | This variable takes precedence over the FetchIt config file and will overwrite its contents if both are provided. 77 | 78 | Methods 79 | ======= 80 | Various methods are available to lifecycle and manage the container environment on a host. Funcionality also exists to 81 | allow for files or directories of files to be deployed to the container host to be used by containers. 82 | 83 | 84 | All methods are defined within specific targetConfiguration sections. These sections are demonstrated below. For private repositories, a PAT token or a username/password combination is required. 85 | 86 | An example of using a PAT token is shown below. 87 | 88 | .. code-block:: yaml 89 | 90 | gitAuth: 91 | pat: CHANGEME 92 | targetConfigs: 93 | - url: https://github.com/containers/fetchit 94 | branch: main 95 | raw: 96 | - name: raw-ex 97 | targetPath: examples/raw 98 | schedule: "*/5 * * * *" 99 | pullImage: true 100 | 101 | A SSH key can also be used for the cloning of a repository. An example of using an SSH key is shown below. 102 | 103 | NOTE: The key must be defined within your git provider to be able to be used for pulling. 104 | 105 | .. code-block:: bash 106 | 107 | mkdir -p ~/.fetchit/.ssh 108 | cp -rp ~/.ssh/id_rsa ~/.fetchit/.ssh/id_rsa 109 | chmod 0600 -R ~/.fetchit/.ssh 110 | ssh-keyscan -t ecdsa github.com >> ~/.fetchit/.ssh/known_hosts 111 | ssh-keyscan -t rsa github.com > ~/.fetchit/.ssh/known_hosts 112 | 113 | 114 | The configuration file to use the key is shown below. 115 | 116 | .. code-block:: yaml 117 | 118 | gitAuth: 119 | ssh: true 120 | sshKeyFile: id_rsa 121 | targetConfigs: 122 | - url: git@github.com:containers/fetchit 123 | raw: 124 | - name: raw-ex 125 | targetPath: examples/raw 126 | schedule: "*/5 * * * *" 127 | pullImage: true 128 | 129 | 130 | An example of using username/password is shown below. 131 | 132 | .. code-block:: yaml 133 | 134 | gitAuth: 135 | username: bob 136 | password: bobpassword 137 | targetConfigs: 138 | - url: https://github.com/containers/fetchit 139 | branch: main 140 | raw: 141 | - name: raw-ex 142 | targetPath: examples/raw 143 | schedule: "*/5 * * * *" 144 | pullImage: true 145 | 146 | Podman secrets can also be used but FetchIt must be started with the secret defined as an environment variable. 147 | This variable is defined as `--secret GH_PAT,type=env` in the `podman run` command. 148 | 149 | .. code-block:: bash 150 | 151 | export GH_PAT_TOKEN=CHANGEME 152 | podman secret create --env GH_PAT GH_PAT_TOKEN 153 | podman run -d --name fetchit -v fetchit-volume:/opt -v $HOME/.fetchit:/opt/mount -v /run/user/1000/podman/podman.sock:/run/podman/podman.sock --secret GH_PAT,type=env --security-opt label=disable --secret GH_PAT,type=env quay.io/fetchit/fetchit:latest 154 | 155 | Ansible 156 | ------- 157 | The AnsibleTarget method allows for an Ansible playbook to be run on the host. A container is created containing the Ansible playbook, and the container will run the playbook. This playbook can be used to install software, configure the host, or perform other tasks. 158 | In the examples directory, there is an Ansible playbook that is used to install zsh. 159 | 160 | .. code-block:: yaml 161 | 162 | targetConfigs: 163 | - url: https://github.com/containers/fetchit 164 | branch: main 165 | ansible: 166 | - name: ans-ex 167 | targetPath: examples/ansible 168 | sshDirectory: /root/.ssh 169 | schedule: "*/5 * * * *" 170 | 171 | The field sshDirectory is unique for this method. This directory should contain the private key used to connect to the host and the public key should be copied into the `.ssh/authorized_keys` file to allow for connectivity. The .ssh directory should be owned by root. 172 | 173 | Raw 174 | --- 175 | The RawTarget method will launch containers based upon their definition in a JSON file. This method is the equivalent of using the `podman run` command on the host. Multiple JSON files can be defined within a directory. 176 | 177 | .. code-block:: yaml 178 | 179 | targetConfigs: 180 | - url: https://github.com/containers/fetchit 181 | branch: main 182 | raw: 183 | - name: raw-ex 184 | targetPath: examples/raw 185 | schedule: "*/5 * * * *" 186 | pullImage: true 187 | 188 | The pullImage field is useful if a container image uses the latest tag. This will ensure that the method will attempt to pull the container image every time. 189 | 190 | A Raw JSON file can contain the following fields. 191 | 192 | .. code-block:: json 193 | 194 | { 195 | "Image":"docker.io/mmumshad/simple-webapp-color:latest", 196 | "Name": "colors1", 197 | "Env": {"APP_COLOR": "pink", "tree": "trunk"}, 198 | "Mounts": "", 199 | "Volumes": "", 200 | "Ports": [{ 201 | "host_ip": "", 202 | "container_port": 8080, 203 | "host_port": 8080, 204 | "range": 0, 205 | "protocol": ""}] 206 | } 207 | 208 | Volume and host mounts can be provided in the JSON file. 209 | 210 | PodmanAutoUpdate 211 | ------- 212 | If this method is present in the config file, podman-auto-update.service & podman-auto-update.timer 213 | will be enabled on the host. Podman auto-update will look for image updates with all podman-generated unit files 214 | that include the auto-update label, according to the timer schedule. Can configure for root, non-root, or both. 215 | 216 | .. code-block:: yaml 217 | 218 | podmanAutoUpdate: 219 | root: true 220 | user: true 221 | 222 | Systemd 223 | ------- 224 | SystemdTarget is a method that will place, enable, and restart systemd unit files. 225 | 226 | .. code-block:: yaml 227 | 228 | targetConfigs: 229 | - url: https://github.com/containers/fetchit 230 | branch: main 231 | systemd: 232 | - name: sysd-ex 233 | targetPath: examples/systemd 234 | root: true 235 | enable: true 236 | schedule: "*/5 * * * *" 237 | 238 | File Transfer 239 | ------------- 240 | The File Transfer method will copy files from the container to the host. This method is useful for transferring files from the container to the host to be used by the container either at start up or during runtime. 241 | 242 | .. code-block:: yaml 243 | 244 | targetConfigs: 245 | - url: https://github.com/containers/fetchit 246 | filetransfer: 247 | - name: ft-ex 248 | targetPath: examples/filetransfer 249 | destinationDirectory: /tmp/ft 250 | schedule: "*/5 * * * *" 251 | branch: main 252 | 253 | The destinationDirectory field is the directory on the host where the files will be copied to. 254 | 255 | Kube Play 256 | --------- 257 | The KubeTarget method will launch a container based upon a Kubernetes pod manifest. This is useful for launching containers to run the same way as they would in a Kubernetes environment. 258 | 259 | .. code-block:: yaml 260 | 261 | targetConfigs: 262 | - url: https://github.com/containers/fetchit 263 | kube: 264 | - name: kube-ex 265 | targetPath: examples/kube 266 | schedule: "*/5 * * * *" 267 | branch: main 268 | 269 | An example Kube play YAML file will look similiar to the following. This will launch a container as well as the coresponding ConfigMap. 270 | 271 | .. code-block:: yaml 272 | 273 | apiVersion: v1 274 | kind: ConfigMap 275 | metadata: 276 | name: env 277 | data: 278 | APP_COLOR: red 279 | tree: trunk 280 | --- 281 | apiVersion: v1 282 | kind: Pod 283 | metadata: 284 | name: colors_pod 285 | spec: 286 | containers: 287 | - name: colors-kubeplay 288 | image: docker.io/mmumshad/simple-webapp-color:latest 289 | ports: 290 | - containerPort: 8080 291 | hostPort: 7080 292 | envFrom: 293 | - configMapRef: 294 | name: env 295 | optional: false 296 | -------------------------------------------------------------------------------- /docs/purpose.rst: -------------------------------------------------------------------------------- 1 | Purpose 2 | ======= 3 | 4 | With the adoption of GitOps tools such as ArgoCD and Red Hat Advanced Cluster Management for Kubernetes(RHACM) a very mature set of tools have been established allowing for the lifecycle management of containers running on Kubernetes. A technical gap exists for those environments running containers on the host without Kubernetes. Tools like Ansible can deploy updates to a container and lifecycle the application but this requires a playbook to be dynamically generated and ran on the host through GitHub actions or using tools such as Ansible Automation Platform. However, these tools do not offer a solution that matches the features and functionality of ArgoCD and RHACM because a host or localhost is required to act as a intermediary between the git repository and the host in which the containers are running. 5 | 6 | This gap provides the opportunity for a tool to be written specifically for the management of a container's lifecycle. The purpose of the FetchIt project is to allow for the definition of a container(s) that defines the required ports, volumes, environment variables, and mounts. This definition can be updated and submitted to a git repository. FetchIt will notice that changes to the container are required based on the git commit history and deploy the new container as it is defined in git. 7 | 8 | Why FetchIt? 9 | ------------ 10 | 11 | FetchIt allows for a GitOps based approach to manage containers running on a single host or multiple hosts based on a git repository. This allows for us to deploy a new host and provide the host a configuration value for FetchIt and automatically any containers defined in the git repository and branch will be deployed onto the host. This can be beneficial for environments that do not require the complexity of Kubernetes to manage the containers running on the host. 12 | 13 | The lifecycle of containers can and should be an automated process. Because changes to a containerized application can occur many times a day the process to modify a running container or deploy new containers should automatically occur. 14 | 15 | How 16 | --- 17 | 18 | FetchIt operates by running a binary or in a container on a host. FetchIt is given a configuration file which defines the way a container is deployed(engine), a repository, a specific branch within the repository, and additional variables used by the engine to lifecycle a container(s). Within the configuration file also exists a schedule based upon cron specifications. This schedule tells FetchIt when and how frequently to perform a git pull of a repository to look for changed objects. 19 | 20 | The FetchIt engine defines a specific method and specification to deploy a container. For example, we would want a specific process to deploy a container(s) based on the Podman pod specification. Various engines will be created to allow for the lifecycle management of containers regardless of the process in which they were deployed on the host. 21 | 22 | Podman allows for the usage of a socket to deploy, stop, and remove containers. This socket can be enabled for users which allows for FetchIt to run without the need for privilege escalation. 23 | -------------------------------------------------------------------------------- /docs/quick_start.rst: -------------------------------------------------------------------------------- 1 | Quick Start 2 | ============ 3 | If you want to to try FetchIt out run the following commands. This document will assume that the OS is Fedora, CentOS, or RHEL but FetchIt is also tested on Ubuntu. The only requirement is Podman v4. 4 | 5 | We will assume that FetchIt will be ran as a non-privileged user. The first step will be to install Podman. 6 | 7 | .. code-block:: bash 8 | 9 | sudo dnf -y podman 10 | systemctl start podman.socket --user 11 | 12 | Now that Podman is available and the Podman socket is running, we can use FetchIt to manage containers. Start by creating the directory that will hold the FetchIt configuration. 13 | 14 | .. code-block:: bash 15 | 16 | mkdir ~/.fetchit 17 | 18 | 19 | Next, create a configuration file. 20 | 21 | .. code-block:: bash 22 | 23 | vi ~/.fetchit/config.yaml 24 | 25 | .. code-block:: yaml 26 | 27 | targetConfigs: 28 | - url: https://github.com/containers/fetchit 29 | raw: 30 | - name: welcome-to-fetchit 31 | targetPath: examples/single-raw 32 | schedule: "*/1 * * * *" 33 | pullImage: true 34 | branch: main 35 | 36 | Finally, run FetchIt. 37 | 38 | .. code-block:: bash 39 | 40 | podman run -d --rm --name fetchit -v fetchit-volume:/opt -v $HOME/.fetchit:/opt/mount -v /run/user/$(id -u)/podman/podman.sock:/run/podman/podman.sock --security-opt label=disable quay.io/fetchit/fetchit:latest 41 | 42 | 43 | To view the running containers, run the following command. 44 | 45 | .. code-block:: bash 46 | 47 | podman ps 48 | 49 | The sample application can be found by visting the following URL `on your localhost `_ 50 | 51 | 52 | With this demonstration in mind you can fork the FetchIt repository or create your own repository and start defining your own applications for FetchIt. 53 | 54 | Any changes that you make to the configuration file require a restart of the FetchIt container. 55 | 56 | -------------------------------------------------------------------------------- /docs/running.rst: -------------------------------------------------------------------------------- 1 | 2 | 3 | Running 4 | ============ 5 | For running the engine the podman socket must be enabled. This can be enabled for the user account that will be running fetchit or for root. 6 | 7 | User 8 | ---- 9 | For regular user accounts run the following to enable the socket. 10 | 11 | .. code-block:: bash 12 | 13 | systemctl --user enable --now podman.socket 14 | 15 | Within */run* a process will be started for the user to interact with the podman socket. Using your UID you can idenitfy the socket. 16 | 17 | .. code-block:: bash 18 | 19 | export DOCKER_HOST=unix:///run/user/$(id -u)/podman/podman.sock 20 | 21 | Root 22 | ---- 23 | For the root user enable the socket by running the following. 24 | 25 | .. code-block:: bash 26 | 27 | systemctl enable --now podman.socket 28 | 29 | Launching 30 | --------- 31 | The podman engine can be launched by running the following command or by using the systemd files from the repository. Most methods except for systemd can be ran without sudo. 32 | 33 | Systemd 34 | ------- 35 | The two systemd files are differentiated by .root and .user. 36 | 37 | Ensure that the location of the `config.yaml` is correctly defined in the systemd service file before attempting to start the service. 38 | 39 | For root 40 | 41 | .. code-block:: bash 42 | 43 | cp systemd/fetchit-root.service /etc/systemd/system/fetchit.service 44 | systemctl enable fetchit --now 45 | 46 | 47 | For user ensure that the path for the configuration file `/home/fetchiter/config.yaml:/opt/config.yaml` and the path for the podman socket are correct. 48 | 49 | .. code-block:: bash 50 | 51 | mkdir -p ~/.config/systemd/user/ 52 | cp systemd/fetchit-user.service ~/.config/systemd/user/ 53 | systemctl --user enable fetchit --now 54 | 55 | Manually 56 | -------- 57 | 58 | .. code-block:: bash 59 | 60 | podman run -d --name fetchit \ 61 | -v fetchit-volume:/opt \ 62 | -v ./config.yaml:/opt/config.yaml \ 63 | -v /run/user/1000/podman/podman.sock:/run/podman/podman.sock \ 64 | --security-opt label=disable \ 65 | quay.io/fetchit/fetchit:latest 66 | 67 | FetchIt will clone the repository and attempt to remediate those items defined in the config.yaml file. To follow the status. 68 | 69 | .. code-block:: bash 70 | 71 | podman logs -f fetchit 72 | 73 | -------------------------------------------------------------------------------- /examples/ansible.yaml: -------------------------------------------------------------------------------- 1 | targetConfigs: 2 | - url: https://github.com/containers/fetchit 3 | ansible: 4 | - name: ansible 5 | targetPath: examples/ansible 6 | sshDirectory: /root/.ssh 7 | schedule: "*/1 * * * *" 8 | branch: main 9 | -------------------------------------------------------------------------------- /examples/ansible/playbook.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: localhost 3 | become: true 4 | tasks: 5 | - name: zsh install 6 | ansible.builtin.package: name=zsh state=latest -------------------------------------------------------------------------------- /examples/ci-config.yaml: -------------------------------------------------------------------------------- 1 | targetConfigs: 2 | - url: https://github.com/containers/fetchit 3 | raw: 4 | - name: raw 5 | targetPath: examples/raw 6 | schedule: "*/1 * * * *" 7 | branch: ci 8 | -------------------------------------------------------------------------------- /examples/ci-filetransfer-config.yaml: -------------------------------------------------------------------------------- 1 | targetConfigs: 2 | - url: https://github.com/containers/fetchit 3 | filetransfer: 4 | - name: ft-example 5 | targetPath: examples/filetransfer 6 | destinationDirectory: /tmp/ft 7 | schedule: "*/1 * * * *" 8 | branch: ci 9 | -------------------------------------------------------------------------------- /examples/clean-config.yaml: -------------------------------------------------------------------------------- 1 | prune: 2 | All: true 3 | Volumes: true 4 | schedule: "*/1 * * * *" 5 | -------------------------------------------------------------------------------- /examples/config-reload.yaml: -------------------------------------------------------------------------------- 1 | # for this test, start with this config, then wait to be sure the 2 | # targetConfigs from .fetchit/config.yaml are populated 3 | # and for follow-up test, push a change to the config and confirm 4 | # new targetConfigs are fetched & run 5 | configReload: 6 | configURL: https://raw.githubusercontent.com/containers/fetchit/main/examples/config-reload.yaml 7 | schedule: "*/2 * * * *" 8 | targetConfigs: 9 | - url: https://github.com/containers/fetchit 10 | raw: 11 | - name: raw-ex 12 | targetPath: examples/raw 13 | schedule: "*/1 * * * *" 14 | pullImage: false 15 | branch: main 16 | -------------------------------------------------------------------------------- /examples/config-url.yaml: -------------------------------------------------------------------------------- 1 | # This is an example configReload that is used in testing. Fetchit will start with this config then will load targetConfigs from ./examples/config-reload.yaml 2 | # Note: It takes (default) 5 min for raw urls to be updated in GitHub, so this test will wait for 7 min 3 | configReload: 4 | configURL: https://raw.githubusercontent.com/containers/fetchit/main/examples/config-reload.yaml 5 | schedule: "*/1 * * * *" 6 | -------------------------------------------------------------------------------- /examples/filetransfer-config-single-file.yaml: -------------------------------------------------------------------------------- 1 | targetConfigs: 2 | - url: https://github.com/containers/fetchit 3 | filetransfer: 4 | - name: ft-ex 5 | targetPath: examples/filetransfer 6 | glob: "hello.txt" 7 | destinationDirectory: /tmp/ft/single 8 | schedule: "*/1 * * * *" 9 | branch: main 10 | -------------------------------------------------------------------------------- /examples/filetransfer-config.yaml: -------------------------------------------------------------------------------- 1 | targetConfigs: 2 | - url: https://github.com/containers/fetchit 3 | filetransfer: 4 | - name: ft-ex 5 | targetPath: examples/filetransfer 6 | destinationDirectory: /tmp/ft 7 | schedule: "*/1 * * * *" 8 | branch: main 9 | -------------------------------------------------------------------------------- /examples/filetransfer/anotherfile.txt: -------------------------------------------------------------------------------- 1 | this is another file 2 | -------------------------------------------------------------------------------- /examples/filetransfer/hello.txt: -------------------------------------------------------------------------------- 1 | hello from filetransfer method 2 | -------------------------------------------------------------------------------- /examples/full-suite-disconnected-usb.yaml: -------------------------------------------------------------------------------- 1 | targetConfigs: 2 | - disconnected: true 3 | device: /dev/sda1 4 | raw: 5 | - name: raw-ex 6 | targetPath: examples/raw 7 | schedule: "*/1 * * * *" 8 | pullImage: false 9 | systemd: 10 | - name: sysd-ex 11 | targetPath: examples/systemd 12 | root: true 13 | enable: false 14 | schedule: "*/1 * * * *" 15 | ansible: 16 | - name: ans-ex 17 | targetPath: examples/ansible 18 | sshDirectory: /root/.ssh 19 | schedule: "*/1 * * * *" 20 | filetransfer: 21 | - name: ft-ex 22 | targetPath: examples/filetransfer 23 | destinationDirectory: /tmp/ft 24 | schedule: "*/1 * * * *" 25 | branch: main 26 | -------------------------------------------------------------------------------- /examples/full-suite-disconnected.yaml: -------------------------------------------------------------------------------- 1 | targetConfigs: 2 | - disconnected: true 3 | url: http://localhost:9000/fetchit.zip 4 | raw: 5 | - name: raw-ex 6 | targetPath: examples/raw 7 | schedule: "*/1 * * * *" 8 | pullImage: false 9 | systemd: 10 | - name: sysd-ex 11 | targetPath: examples/systemd 12 | root: true 13 | enable: false 14 | schedule: "*/1 * * * *" 15 | ansible: 16 | - name: ans-ex 17 | targetPath: examples/ansible 18 | sshDirectory: /root/.ssh 19 | schedule: "*/1 * * * *" 20 | filetransfer: 21 | - name: ft-ex 22 | targetPath: examples/filetransfer 23 | destinationDirectory: /tmp/ft 24 | schedule: "*/1 * * * *" 25 | branch: main 26 | -------------------------------------------------------------------------------- /examples/full-suite-with-skew.yaml: -------------------------------------------------------------------------------- 1 | targetConfigs: 2 | - url: https://github.com/containers/fetchit 3 | raw: 4 | - name: raw-ex 5 | targetPath: examples/raw 6 | schedule: "*/1 * * * *" 7 | skew: 10000 8 | pullImage: false 9 | systemd: 10 | - name: sysd-ex 11 | targetPath: examples/systemd 12 | root: true 13 | enable: false 14 | schedule: "*/1 * * * *" 15 | skew: 1000 16 | ansible: 17 | - name: ans-ex 18 | targetPath: examples/ansible 19 | sshDirectory: /root/.ssh 20 | schedule: "*/1 * * * *" 21 | filetransfer: 22 | - name: ft-ex 23 | targetPath: examples/filetransfer 24 | destinationDirectory: /tmp/ft 25 | schedule: "*/1 * * * *" 26 | skew: 3000 27 | branch: main 28 | -------------------------------------------------------------------------------- /examples/full-suite.yaml: -------------------------------------------------------------------------------- 1 | prune: 2 | All: true 3 | Volumes: false 4 | schedule: "*/1 * * * *" 5 | targetConfigs: 6 | - url: https://github.com/containers/fetchit 7 | raw: 8 | - name: raw-ex 9 | targetPath: examples/raw 10 | schedule: "*/1 * * * *" 11 | pullImage: false 12 | systemd: 13 | - name: sysd-ex 14 | targetPath: examples/systemd 15 | root: true 16 | enable: false 17 | schedule: "*/1 * * * *" 18 | ansible: 19 | - name: ans-ex 20 | targetPath: examples/ansible 21 | sshDirectory: /root/.ssh 22 | schedule: "*/1 * * * *" 23 | filetransfer: 24 | - name: ft-ex 25 | targetPath: examples/filetransfer 26 | destinationDirectory: /tmp/ft 27 | schedule: "*/1 * * * *" 28 | branch: main 29 | -------------------------------------------------------------------------------- /examples/gitsign-verify-config.yaml: -------------------------------------------------------------------------------- 1 | targetConfigs: 2 | - url: https://github.com/sallyom/fetchit 3 | verifyCommitsInfo: 4 | GitsignVerify: true 5 | filetransfer: 6 | - name: ft-ex 7 | targetPath: examples/filetransfer 8 | destinationDirectory: /tmp/ft 9 | schedule: "*/1 * * * *" 10 | branch: gitsign 11 | -------------------------------------------------------------------------------- /examples/glob-config.yaml: -------------------------------------------------------------------------------- 1 | targetConfigs: 2 | - url: https://github.com/josephsawaya/fetchit 3 | raw: 4 | - name: raw-ex 5 | targetPath: examples/raw 6 | glob: "*.json" 7 | schedule: "*/1 * * * *" 8 | pullImage: false 9 | branch: fix-target-path 10 | -------------------------------------------------------------------------------- /examples/imageLoad-config.yaml: -------------------------------------------------------------------------------- 1 | images: 2 | - name: httpd-ex 3 | url: http://localhost:8080/httpd.tar 4 | schedule: "*/1 * * * *" 5 | targetConfigs: 6 | - url: https://github.com/containers/fetchit 7 | raw: 8 | - name: raw-ex 9 | targetPath: examples/imageLoad 10 | schedule: "*/1 * * * *" 11 | pullImage: false 12 | branch: main 13 | -------------------------------------------------------------------------------- /examples/imageLoad/byo-image.yaml: -------------------------------------------------------------------------------- 1 | { 2 | "Image":"quay.io/notreal/httpd:latest", 3 | "Name": "local", 4 | "Ports": [{ 5 | "host_ip": "", 6 | "container_port": 8080, 7 | "host_port": 9090, 8 | "range": 0, 9 | "protocol": ""}] 10 | } 11 | -------------------------------------------------------------------------------- /examples/kube-play-config.yaml: -------------------------------------------------------------------------------- 1 | targetConfigs: 2 | - url: https://github.com/containers/fetchit 3 | kube: 4 | - name: kube-ex 5 | targetPath: examples/kube 6 | schedule: "*/1 * * * *" 7 | branch: main 8 | -------------------------------------------------------------------------------- /examples/kube/1-pvc.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: PersistentVolumeClaim 3 | metadata: 4 | name: task-pv-claim 5 | -------------------------------------------------------------------------------- /examples/kube/2-example.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: nginx-pod 5 | spec: 6 | volumes: 7 | - name: task-pv-storage 8 | persistentVolumeClaim: 9 | claimName: task-pv-claim 10 | containers: 11 | - name: nginx-server 12 | image: docker.io/nginx:latest 13 | ports: 14 | - containerPort: 80 15 | hostPort: 8080 16 | volumeMounts: 17 | - mountPath: "/usr/share/nginx/html" 18 | name: task-pv-storage 19 | -------------------------------------------------------------------------------- /examples/kube/3-example.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ConfigMap 3 | metadata: 4 | name: env 5 | data: 6 | APP_COLOR: blue 7 | tree: trunk 8 | --- 9 | apiVersion: v1 10 | kind: Pod 11 | metadata: 12 | name: colors_pod 13 | spec: 14 | containers: 15 | - name: colors-kubeplay 16 | image: docker.io/mmumshad/simple-webapp-color:latest 17 | ports: 18 | - containerPort: 8080 19 | hostPort: 7080 20 | envFrom: 21 | - configMapRef: 22 | name: env 23 | optional: false 24 | -------------------------------------------------------------------------------- /examples/pat-testing-config.yaml: -------------------------------------------------------------------------------- 1 | # for this test, start with this config, then wait to be sure the 2 | # targetConfigs from .fetchit/config.yaml are populated 3 | # and for follow-up test, push a change to the config and confirm 4 | # new targetConfigs are fetched & run 5 | configReload: 6 | configURL: https://raw.githubusercontent.com/containers/fetchit/main/examples/config-reload.yaml 7 | schedule: "*/2 * * * *" 8 | gitAuth: 9 | pat: CHANGEME 10 | targetConfigs: 11 | - url: https://github.com/containers/fetchit 12 | raw: 13 | - name: raw-ex 14 | targetPath: examples/raw 15 | schedule: "*/1 * * * *" 16 | pullImage: false 17 | branch: main 18 | -------------------------------------------------------------------------------- /examples/pat-testing-kube.yaml: -------------------------------------------------------------------------------- 1 | # for this test, start with this config, then wait to be sure the 2 | # targetConfigs from .fetchit/config.yaml are populated 3 | # and for follow-up test, push a change to the config and confirm 4 | # new targetConfigs are fetched & run 5 | gitAuth: 6 | pat: CHANGEME 7 | targetConfigs: 8 | - url: https://github.com/containers/fetchit 9 | kube: 10 | - name: kube-ex 11 | targetPath: examples/kube 12 | schedule: "*/1 * * * *" 13 | branch: main 14 | -------------------------------------------------------------------------------- /examples/podman-secret-raw-config.yaml: -------------------------------------------------------------------------------- 1 | # for this test, start with this config, Using a podman secret 2 | # then wait to be sure the 3 | # targetConfigs from .fetchit/config.yaml are populated 4 | # and for follow-up test, push a change to the config and confirm 5 | # new targetConfigs are fetched & run 6 | configReload: 7 | configURL: https://raw.githubusercontent.com/containers/fetchit/main/examples/config-reload.yaml 8 | schedule: "*/2 * * * *" 9 | gitAuth: 10 | envSecret: GH_PAT 11 | targetConfigs: 12 | - url: https://github.com/containers/fetchit 13 | raw: 14 | - name: raw 15 | targetPath: examples/raw 16 | schedule: "*/1 * * * *" 17 | branch: main 18 | -------------------------------------------------------------------------------- /examples/podman-secret-raw.yaml: -------------------------------------------------------------------------------- 1 | # for this test, use of a podman secret with a raw target 2 | gitAuth: 3 | envSecret: GH_PAT 4 | targetConfigs: 5 | - url: https://github.com/containers/fetchit 6 | raw: 7 | - name: raw 8 | targetPath: examples/raw 9 | schedule: "*/1 * * * *" 10 | branch: main 11 | -------------------------------------------------------------------------------- /examples/raw-config.yaml: -------------------------------------------------------------------------------- 1 | targetConfigs: 2 | - url: https://github.com/containers/fetchit 3 | raw: 4 | - name: raw-ex 5 | targetPath: examples/raw 6 | schedule: "*/1 * * * *" 7 | pullImage: false 8 | branch: main 9 | -------------------------------------------------------------------------------- /examples/raw/cap.json: -------------------------------------------------------------------------------- 1 | { 2 | "Image":"docker.io/mmumshad/simple-webapp-color:latest", 3 | "Name": "cap1", 4 | "Env": {"APP_COLOR": "blue", "tree": "trunk"}, 5 | "Mounts": [], 6 | "Volumes": [], 7 | "CapAdd": ["NET_ADMIN"], 8 | "Ports": [{ 9 | "host_ip": "", 10 | "container_port": 8080, 11 | "host_port": 7070, 12 | "range": 0, 13 | "protocol": ""}] 14 | } 15 | -------------------------------------------------------------------------------- /examples/raw/cap.yaml: -------------------------------------------------------------------------------- 1 | { 2 | "Image":"docker.io/mmumshad/simple-webapp-color:latest", 3 | "Name": "cap2", 4 | "Env": {"APP_COLOR": "blue", "tree": "trunk"}, 5 | "Mounts": [], 6 | "Volumes": [], 7 | "CapDrop": ["all"], 8 | "Ports": [{ 9 | "host_ip": "", 10 | "container_port": 8080, 11 | "host_port": 9090, 12 | "range": 0, 13 | "protocol": ""}] 14 | } 15 | -------------------------------------------------------------------------------- /examples/raw/color1.json: -------------------------------------------------------------------------------- 1 | { 2 | "Image":"docker.io/mmumshad/simple-webapp-color:latest", 3 | "Name": "colors1", 4 | "Env": {"APP_COLOR": "blue", "tree": "trunk"}, 5 | "Mounts": [], 6 | "Volumes": [], 7 | "Ports": [{ 8 | "host_ip": "", 9 | "container_port": 8080, 10 | "host_port": 8080, 11 | "range": 0, 12 | "protocol": ""}] 13 | } -------------------------------------------------------------------------------- /examples/raw/color2.yaml: -------------------------------------------------------------------------------- 1 | Image: "docker.io/mmumshad/simple-webapp-color:latest" 2 | Name: "colors2" 3 | Env: 4 | APP_COLOR: "pink" 5 | tree: "trunk" 6 | Ports: 7 | - container_port: 8080 8 | host_port: 9080 9 | range: 0 10 | -------------------------------------------------------------------------------- /examples/readme-config.yaml: -------------------------------------------------------------------------------- 1 | targetConfigs: 2 | - url: https://github.com/containers/fetchit 3 | branch: main 4 | filetransfer: 5 | - name: ft-ex 6 | targetPath: examples/filetransfer 7 | glob: "hello.txt" 8 | destinationDirectory: /tmp 9 | schedule: "*/1 * * * *" 10 | raw: 11 | - name: raw-ex 12 | targetPath: examples/raw 13 | schedule: "*/1 * * * *" 14 | -------------------------------------------------------------------------------- /examples/single-raw/welcome.yaml: -------------------------------------------------------------------------------- 1 | Image: quay.io/fetchit/fetchit-sample-app:latest 2 | Name: welcome 3 | Ports: 4 | - container_port: 80 5 | host_port: 9191 6 | range: 0 7 | -------------------------------------------------------------------------------- /examples/ssh-config.yaml: -------------------------------------------------------------------------------- 1 | gitAuth: 2 | ssh: true 3 | sshKeyFile: id_rsa 4 | targetConfigs: 5 | - url: git@github.com:containers/fetchit 6 | filetransfer: 7 | - name: ft-ex 8 | targetPath: examples/filetransfer 9 | destinationDirectory: /tmp 10 | schedule: "*/1 * * * *" 11 | branch: main -------------------------------------------------------------------------------- /examples/systemd-autoupdate.yaml: -------------------------------------------------------------------------------- 1 | podmanAutoUpdate: 2 | root: true 3 | targetConfigs: 4 | - url: https://github.com/containers/fetchit 5 | systemd: 6 | - name: sysd-ex 7 | targetPath: examples/systemd 8 | root: true 9 | enable: true 10 | schedule: "*/5 * * * *" 11 | branch: main 12 | -------------------------------------------------------------------------------- /examples/systemd-config-single-file.yaml: -------------------------------------------------------------------------------- 1 | targetConfigs: 2 | - url: https://github.com/containers/fetchit 3 | systemd: 4 | - name: sysd-ex 5 | targetPath: examples/systemd 6 | root: true 7 | enable: false 8 | schedule: "*/1 * * * *" 9 | branch: main 10 | -------------------------------------------------------------------------------- /examples/systemd-config.yaml: -------------------------------------------------------------------------------- 1 | targetConfigs: 2 | - url: https://github.com/containers/fetchit 3 | systemd: 4 | - name: sysd-ex 5 | targetPath: examples/systemd 6 | root: true 7 | enable: false 8 | schedule: "*/1 * * * *" 9 | branch: main 10 | -------------------------------------------------------------------------------- /examples/systemd-enable-user.yaml: -------------------------------------------------------------------------------- 1 | targetConfigs: 2 | - url: https://github.com/containers/fetchit 3 | systemd: 4 | - name: httpd-user 5 | targetPath: examples/systemd 6 | root: false 7 | enable: true 8 | schedule: "*/1 * * * *" 9 | branch: main 10 | 11 | -------------------------------------------------------------------------------- /examples/systemd-enable.yaml: -------------------------------------------------------------------------------- 1 | targetConfigs: 2 | - url: https://github.com/containers/fetchit 3 | systemd: 4 | - name: httpd-root 5 | targetPath: examples/systemd 6 | root: true 7 | enable: true 8 | schedule: "*/1 * * * *" 9 | branch: main 10 | -------------------------------------------------------------------------------- /examples/systemd-restart.yaml: -------------------------------------------------------------------------------- 1 | targetConfigs: 2 | - url: https://github.com/containers/fetchit 3 | systemd: 4 | - name: sysd-ex 5 | targetPath: examples/systemd 6 | root: true 7 | enable: true 8 | restart: true 9 | schedule: "*/1 * * * *" 10 | branch: main 11 | -------------------------------------------------------------------------------- /examples/systemd/httpd.service: -------------------------------------------------------------------------------- 1 | # container-httpd.service 2 | # autogenerated by Podman 3.3.1 3 | # Wed Sep 8 20:41:44 CEST 2021 4 | 5 | [Unit] 6 | Description=Podman container-httpd.service 7 | Documentation=man:podman-generate-systemd(1) 8 | Wants=network-online.target 9 | After=network-online.target 10 | RequiresMountsFor=%t/containers 11 | 12 | [Service] 13 | Environment=PODMAN_SYSTEMD_UNIT=%n 14 | Restart=on-failure 15 | TimeoutStopSec=70 16 | ExecStartPre=/bin/rm -f %t/%n.ctr-id 17 | ExecStart=/usr/bin/podman run --cidfile=%t/%n.ctr-id --sdnotify=conmon --cgroups=no-conmon --rm -d --replace --label io.containers.autoupdate=local --name httpd -p 8080:8080 registry.access.redhat.com/ubi8/httpd-24:latest 18 | ExecStop=/usr/bin/podman stop --ignore --cidfile=%t/%n.ctr-id 19 | ExecStopPost=/usr/bin/podman rm -f --ignore --cidfile=%t/%n.ctr-id 20 | Type=notify 21 | NotifyAccess=all 22 | 23 | [Install] 24 | WantedBy=multi-user.target default.target 25 | -------------------------------------------------------------------------------- /examples/systemd/podman-auto-update.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Podman auto-update service 3 | Documentation=man:podman-auto-update(1) 4 | Wants=network-online.target 5 | After=network-online.target 6 | 7 | [Service] 8 | Type=oneshot 9 | ExecStart=/usr/bin/podman auto-update 10 | ExecStartPost=/usr/bin/podman image prune -f 11 | 12 | [Install] 13 | WantedBy=default.target 14 | -------------------------------------------------------------------------------- /examples/systemd/podman-auto-update.timer: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Podman auto-update timer 3 | 4 | [Timer] 5 | OnCalendar=daily 6 | RandomizedDelaySec=900 7 | Persistent=true 8 | 9 | [Install] 10 | WantedBy=timers.target 11 | -------------------------------------------------------------------------------- /examples/systemd/podman-auto-update.timer.d-override.conf: -------------------------------------------------------------------------------- 1 | [Timer] 2 | OnCalendar=*-*-* *:00,02,04,06,08,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58:00 3 | RandomizedDelaySec=3 4 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/containers/fetchit 2 | 3 | go 1.17 4 | 5 | require ( 6 | github.com/containers/common v0.49.1 7 | github.com/containers/podman/v4 v4.2.0 8 | github.com/go-co-op/gocron v1.13.0 9 | github.com/go-git/go-git/v5 v5.11.0 10 | github.com/gobwas/glob v0.2.3 11 | github.com/natefinch/lumberjack v2.0.0+incompatible 12 | github.com/opencontainers/runtime-spec v1.0.3-0.20211214071223-8958f93039ab 13 | github.com/openshift/build-machinery-go v0.0.0-20220121085309-f94edc2d6874 14 | github.com/sigstore/gitsign v0.3.0 15 | github.com/sigstore/rekor v0.11.0 16 | github.com/spf13/cobra v1.5.0 17 | github.com/spf13/viper v1.13.0 18 | go.uber.org/zap v1.22.0 19 | gopkg.in/yaml.v3 v3.0.1 20 | k8s.io/api v0.23.5 21 | k8s.io/apimachinery v0.23.5 22 | sigs.k8s.io/yaml v1.3.0 23 | ) 24 | 25 | require ( 26 | bitbucket.org/creachadair/shell v0.0.7 // indirect 27 | cloud.google.com/go/compute v1.15.1 // indirect 28 | cloud.google.com/go/compute/metadata v0.2.3 // indirect 29 | dario.cat/mergo v1.0.0 // indirect 30 | github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect 31 | github.com/BurntSushi/toml v1.2.0 // indirect 32 | github.com/Microsoft/go-winio v0.6.1 // indirect 33 | github.com/Microsoft/hcsshim v0.9.6 // indirect 34 | github.com/ProtonMail/go-crypto v0.0.0-20230828082145-3c4c8a2d2371 // indirect 35 | github.com/VividCortex/ewma v1.2.0 // indirect 36 | github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d // indirect 37 | github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect 38 | github.com/benbjohnson/clock v1.1.0 // indirect 39 | github.com/beorn7/perks v1.0.1 // indirect 40 | github.com/bgentry/speakeasy v0.1.0 // indirect 41 | github.com/blang/semver v3.5.1+incompatible // indirect 42 | github.com/blang/semver/v4 v4.0.0 // indirect 43 | github.com/cenkalti/backoff/v4 v4.1.3 // indirect 44 | github.com/census-instrumentation/opencensus-proto v0.4.1 // indirect 45 | github.com/cespare/xxhash/v2 v2.2.0 // indirect 46 | github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e // indirect 47 | github.com/cilium/ebpf v0.7.0 // indirect 48 | github.com/cloudflare/circl v1.3.7 // indirect 49 | github.com/cncf/udpa/go v0.0.0-20220112060539-c52dc94e7fbe // indirect 50 | github.com/cncf/xds/go v0.0.0-20230105202645-06c439db220b // indirect 51 | github.com/containerd/cgroups v1.0.4 // indirect 52 | github.com/containerd/containerd v1.6.18 // indirect 53 | github.com/containerd/stargz-snapshotter/estargz v0.12.0 // indirect 54 | github.com/containers/buildah v1.27.4 // indirect 55 | github.com/containers/image/v5 v5.22.1 // indirect 56 | github.com/containers/libtrust v0.0.0-20200511145503-9c3a6c22cd9a // indirect 57 | github.com/containers/ocicrypt v1.1.5 // indirect 58 | github.com/containers/psgo v1.7.2 // indirect 59 | github.com/containers/storage v1.42.1-0.20221104172635-d3b97ec7b760 // indirect 60 | github.com/coreos/go-semver v0.3.0 // indirect 61 | github.com/coreos/go-systemd/v22 v22.3.2 // indirect 62 | github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect 63 | github.com/cyberphone/json-canonicalization v0.0.0-20210823021906-dc406ceaf94b // indirect 64 | github.com/cyphar/filepath-securejoin v0.2.4 // indirect 65 | github.com/davecgh/go-spew v1.1.1 // indirect 66 | github.com/disiqueira/gotree/v3 v3.0.2 // indirect 67 | github.com/docker/cli v20.10.17+incompatible // indirect 68 | github.com/docker/distribution v2.8.2+incompatible // indirect 69 | github.com/docker/docker v24.0.9+incompatible // indirect 70 | github.com/docker/docker-credential-helpers v0.6.4 // indirect 71 | github.com/docker/go-connections v0.4.1-0.20210727194412-58542c764a11 // indirect 72 | github.com/docker/go-metrics v0.0.1 // indirect 73 | github.com/docker/go-units v0.4.0 // indirect 74 | github.com/dustin/go-humanize v1.0.0 // indirect 75 | github.com/emirpasic/gods v1.18.1 // indirect 76 | github.com/envoyproxy/go-control-plane v0.10.3 // indirect 77 | github.com/envoyproxy/protoc-gen-validate v0.9.1 // indirect 78 | github.com/fsnotify/fsnotify v1.5.4 // indirect 79 | github.com/fullstorydev/grpcurl v1.8.6 // indirect 80 | github.com/ghodss/yaml v1.0.0 // indirect 81 | github.com/github/smimesign v0.2.0 // indirect 82 | github.com/go-chi/chi v4.1.2+incompatible // indirect 83 | github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect 84 | github.com/go-git/go-billy/v5 v5.5.0 // indirect 85 | github.com/go-logr/logr v1.2.3 // indirect 86 | github.com/go-logr/stdr v1.2.2 // indirect 87 | github.com/go-openapi/analysis v0.21.4 // indirect 88 | github.com/go-openapi/errors v0.20.3 // indirect 89 | github.com/go-openapi/jsonpointer v0.19.5 // indirect 90 | github.com/go-openapi/jsonreference v0.20.0 // indirect 91 | github.com/go-openapi/loads v0.21.2 // indirect 92 | github.com/go-openapi/runtime v0.24.1 // indirect 93 | github.com/go-openapi/spec v0.20.7 // indirect 94 | github.com/go-openapi/strfmt v0.21.3 // indirect 95 | github.com/go-openapi/swag v0.22.3 // indirect 96 | github.com/go-openapi/validate v0.22.0 // indirect 97 | github.com/go-playground/locales v0.14.0 // indirect 98 | github.com/go-playground/universal-translator v0.18.0 // indirect 99 | github.com/go-playground/validator/v10 v10.11.0 // indirect 100 | github.com/godbus/dbus/v5 v5.1.0 // indirect 101 | github.com/gogo/protobuf v1.3.2 // indirect 102 | github.com/golang-jwt/jwt v3.2.2+incompatible // indirect 103 | github.com/golang/glog v1.0.0 // indirect 104 | github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect 105 | github.com/golang/mock v1.6.0 // indirect 106 | github.com/golang/protobuf v1.5.2 // indirect 107 | github.com/golang/snappy v0.0.4 // indirect 108 | github.com/google/btree v1.0.1 // indirect 109 | github.com/google/certificate-transparency-go v1.1.3 // indirect 110 | github.com/google/go-cmp v0.6.0 // indirect 111 | github.com/google/go-containerregistry v0.11.0 // indirect 112 | github.com/google/go-intervals v0.0.2 // indirect 113 | github.com/google/gofuzz v1.2.0 // indirect 114 | github.com/google/trillian v1.4.1 // indirect 115 | github.com/google/uuid v1.3.0 // indirect 116 | github.com/gorilla/mux v1.8.0 // indirect 117 | github.com/gorilla/schema v1.2.0 // indirect 118 | github.com/gorilla/websocket v1.4.2 // indirect 119 | github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect 120 | github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 // indirect 121 | github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect 122 | github.com/grpc-ecosystem/grpc-gateway/v2 v2.11.3 // indirect 123 | github.com/hashicorp/errwrap v1.1.0 // indirect 124 | github.com/hashicorp/go-multierror v1.1.1 // indirect 125 | github.com/hashicorp/hcl v1.0.0 // indirect 126 | github.com/imdario/mergo v0.3.13 // indirect 127 | github.com/in-toto/in-toto-golang v0.3.4-0.20220709202702-fa494aaa0add // indirect 128 | github.com/inconshreveable/mousetrap v1.0.0 // indirect 129 | github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect 130 | github.com/jedisct1/go-minisign v0.0.0-20211028175153-1c139d1cc84b // indirect 131 | github.com/jhump/protoreflect v1.12.0 // indirect 132 | github.com/jinzhu/copier v0.3.5 // indirect 133 | github.com/jonboulle/clockwork v0.3.0 // indirect 134 | github.com/josharian/intern v1.0.0 // indirect 135 | github.com/json-iterator/go v1.1.12 // indirect 136 | github.com/kevinburke/ssh_config v1.2.0 // indirect 137 | github.com/klauspost/compress v1.15.9 // indirect 138 | github.com/klauspost/pgzip v1.2.5 // indirect 139 | github.com/leodido/go-urn v1.2.1 // indirect 140 | github.com/letsencrypt/boulder v0.0.0-20220723181115-27de4befb95e // indirect 141 | github.com/magiconair/properties v1.8.6 // indirect 142 | github.com/mailru/easyjson v0.7.7 // indirect 143 | github.com/manifoldco/promptui v0.9.0 // indirect 144 | github.com/mattn/go-runewidth v0.0.13 // indirect 145 | github.com/mattn/go-shellwords v1.0.12 // indirect 146 | github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect 147 | github.com/miekg/pkcs11 v1.1.1 // indirect 148 | github.com/mistifyio/go-zfs v2.1.2-0.20190413222219-f784269be439+incompatible // indirect 149 | github.com/mitchellh/go-homedir v1.1.0 // indirect 150 | github.com/mitchellh/mapstructure v1.5.0 // indirect 151 | github.com/moby/sys/mountinfo v0.6.2 // indirect 152 | github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect 153 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 154 | github.com/modern-go/reflect2 v1.0.2 // indirect 155 | github.com/nxadm/tail v1.4.8 // indirect 156 | github.com/oklog/ulid v1.3.1 // indirect 157 | github.com/olekukonko/tablewriter v0.0.5 // indirect 158 | github.com/opencontainers/go-digest v1.0.0 // indirect 159 | github.com/opencontainers/image-spec v1.0.3-0.20220114050600-8b9d41f48198 // indirect 160 | github.com/opencontainers/runc v1.1.12 // indirect 161 | github.com/opencontainers/runtime-tools v0.9.1-0.20220714195903-17b3287fafb7 // indirect 162 | github.com/opencontainers/selinux v1.10.2 // indirect 163 | github.com/opentracing/opentracing-go v1.2.0 // indirect 164 | github.com/ostreedev/ostree-go v0.0.0-20210805093236-719684c64e4f // indirect 165 | github.com/pelletier/go-toml v1.9.5 // indirect 166 | github.com/pelletier/go-toml/v2 v2.0.5 // indirect 167 | github.com/pjbgf/sha1cd v0.3.0 // indirect 168 | github.com/pkg/errors v0.9.1 // indirect 169 | github.com/pmezard/go-difflib v1.0.0 // indirect 170 | github.com/proglottis/gpgme v0.1.3 // indirect 171 | github.com/prometheus/client_golang v1.13.0 // indirect 172 | github.com/prometheus/client_model v0.2.0 // indirect 173 | github.com/prometheus/common v0.37.0 // indirect 174 | github.com/prometheus/procfs v0.8.0 // indirect 175 | github.com/rivo/uniseg v0.2.0 // indirect 176 | github.com/robfig/cron/v3 v3.0.1 // indirect 177 | github.com/russross/blackfriday/v2 v2.1.0 // indirect 178 | github.com/sassoftware/relic v0.0.0-20210427151427-dfb082b79b74 // indirect 179 | github.com/secure-systems-lab/go-securesystemslib v0.4.0 // indirect 180 | github.com/sergi/go-diff v1.2.0 // indirect 181 | github.com/shibumi/go-pathspec v1.3.0 // indirect 182 | github.com/sigstore/cosign v1.12.0 // indirect 183 | github.com/sigstore/sigstore v1.4.1-0.20220908204944-ec922cf4f1c2 // indirect 184 | github.com/sirupsen/logrus v1.9.0 // indirect 185 | github.com/skeema/knownhosts v1.2.1 // indirect 186 | github.com/soheilhy/cmux v0.1.5 // indirect 187 | github.com/spf13/afero v1.9.2 // indirect 188 | github.com/spf13/cast v1.5.0 // indirect 189 | github.com/spf13/jwalterweatherman v1.1.0 // indirect 190 | github.com/spf13/pflag v1.0.5 // indirect 191 | github.com/stefanberger/go-pkcs11uri v0.0.0-20201008174630-78d3cae3a980 // indirect 192 | github.com/stretchr/testify v1.8.4 // indirect 193 | github.com/subosito/gotenv v1.4.1 // indirect 194 | github.com/sylabs/sif/v2 v2.8.1 // indirect 195 | github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635 // indirect 196 | github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect 197 | github.com/tchap/go-patricia v2.3.0+incompatible // indirect 198 | github.com/tent/canonical-json-go v0.0.0-20130607151641-96e4ba3a7613 // indirect 199 | github.com/theupdateframework/go-tuf v0.5.0 // indirect 200 | github.com/titanous/rocacheck v0.0.0-20171023193734-afe73141d399 // indirect 201 | github.com/tmc/grpc-websocket-proxy v0.0.0-20201229170055-e5319fda7802 // indirect 202 | github.com/transparency-dev/merkle v0.0.1 // indirect 203 | github.com/ulikunitz/xz v0.5.10 // indirect 204 | github.com/urfave/cli v1.22.7 // indirect 205 | github.com/vbatts/tar-split v0.11.2 // indirect 206 | github.com/vbauerster/mpb/v7 v7.4.2 // indirect 207 | github.com/xanzy/ssh-agent v0.3.3 // indirect 208 | github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect 209 | github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect 210 | github.com/xeipuuv/gojsonschema v1.2.0 // indirect 211 | github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2 // indirect 212 | go.etcd.io/bbolt v1.3.6 // indirect 213 | go.etcd.io/etcd/api/v3 v3.6.0-alpha.0 // indirect 214 | go.etcd.io/etcd/client/pkg/v3 v3.6.0-alpha.0 // indirect 215 | go.etcd.io/etcd/client/v2 v2.306.0-alpha.0 // indirect 216 | go.etcd.io/etcd/client/v3 v3.6.0-alpha.0 // indirect 217 | go.etcd.io/etcd/etcdctl/v3 v3.6.0-alpha.0 // indirect 218 | go.etcd.io/etcd/etcdutl/v3 v3.6.0-alpha.0 // indirect 219 | go.etcd.io/etcd/pkg/v3 v3.6.0-alpha.0 // indirect 220 | go.etcd.io/etcd/raft/v3 v3.6.0-alpha.0 // indirect 221 | go.etcd.io/etcd/server/v3 v3.6.0-alpha.0 // indirect 222 | go.etcd.io/etcd/tests/v3 v3.6.0-alpha.0 // indirect 223 | go.etcd.io/etcd/v3 v3.6.0-alpha.0 // indirect 224 | go.mongodb.org/mongo-driver v1.10.0 // indirect 225 | go.mozilla.org/pkcs7 v0.0.0-20200128120323-432b2356ecb1 // indirect 226 | go.opencensus.io v0.24.0 // indirect 227 | go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.28.0 // indirect 228 | go.opentelemetry.io/otel v1.7.0 // indirect 229 | go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.7.0 // indirect 230 | go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.7.0 // indirect 231 | go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.7.0 // indirect 232 | go.opentelemetry.io/otel/sdk v1.7.0 // indirect 233 | go.opentelemetry.io/otel/trace v1.7.0 // indirect 234 | go.opentelemetry.io/proto/otlp v0.16.0 // indirect 235 | go.uber.org/atomic v1.10.0 // indirect 236 | go.uber.org/multierr v1.8.0 // indirect 237 | golang.org/x/crypto v0.21.0 // indirect 238 | golang.org/x/mod v0.12.0 // indirect 239 | golang.org/x/net v0.23.0 // indirect 240 | golang.org/x/oauth2 v0.4.0 // indirect 241 | golang.org/x/sync v0.3.0 // indirect 242 | golang.org/x/sys v0.18.0 // indirect 243 | golang.org/x/term v0.18.0 // indirect 244 | golang.org/x/text v0.14.0 // indirect 245 | golang.org/x/time v0.1.0 // indirect 246 | golang.org/x/tools v0.13.0 // indirect 247 | google.golang.org/appengine v1.6.7 // indirect 248 | google.golang.org/genproto v0.0.0-20230110181048-76db0878b65f // indirect 249 | google.golang.org/grpc v1.53.0 // indirect 250 | google.golang.org/protobuf v1.33.0 // indirect 251 | gopkg.in/cheggaaa/pb.v1 v1.0.28 // indirect 252 | gopkg.in/inf.v0 v0.9.1 // indirect 253 | gopkg.in/ini.v1 v1.67.0 // indirect 254 | gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect 255 | gopkg.in/square/go-jose.v2 v2.6.0 // indirect 256 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect 257 | gopkg.in/warnings.v0 v0.1.2 // indirect 258 | gopkg.in/yaml.v2 v2.4.0 // indirect 259 | k8s.io/klog/v2 v2.60.1-0.20220317184644-43cc75f9ae89 // indirect 260 | k8s.io/utils v0.0.0-20220210201930-3a6ce19ff2f9 // indirect 261 | sigs.k8s.io/json v0.0.0-20211208200746-9f7c6b3444d2 // indirect 262 | sigs.k8s.io/structured-merge-diff/v4 v4.2.1 // indirect 263 | ) 264 | -------------------------------------------------------------------------------- /method_containers/ansible/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM quay.io/fedora/fedora:36 2 | 3 | ARG ARCH=$ARCH 4 | ARG MAKE_TARGET=cross-build-linux-$ARCH-ansible 5 | 6 | RUN yum -y install openssh-clients ansible && yum clean all 7 | 8 | ADD ansible.cfg /etc/ansible/ 9 | -------------------------------------------------------------------------------- /method_containers/ansible/ansible.cfg: -------------------------------------------------------------------------------- 1 | [defaults] 2 | host_key_checking = False 3 | -------------------------------------------------------------------------------- /method_containers/systemd/Dockerfile-systemctl: -------------------------------------------------------------------------------- 1 | FROM registry.access.redhat.com/ubi8/ubi:latest 2 | USER root 3 | COPY ./method_containers/systemd/systemd-script /opt/systemd-script 4 | ENTRYPOINT ["/opt/systemd-script"] 5 | -------------------------------------------------------------------------------- /method_containers/systemd/systemd-script: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | if [ "$ACTION" == "enable" ]; then 4 | if [ "$ROOT" == "true" ]; then 5 | systemctl daemon-reload 6 | sleep 2 7 | systemctl enable "${SERVICE}" --now 8 | sleep 2 9 | if ! systemctl is-active --quiet "${SERVICE}"; then 10 | exit 1 11 | fi 12 | else 13 | systemctl --user daemon-reload 14 | sleep 2 15 | systemctl --user enable "${SERVICE}" --now 16 | sleep 2 17 | if ! systemctl --user is-active --quiet "${SERVICE}"; then 18 | exit 1 19 | fi 20 | fi 21 | fi 22 | 23 | if [ "$ACTION" == "restart" ]; then 24 | if [ "$ROOT" == "true" ]; then 25 | systemctl daemon-reload 26 | sleep 2 27 | systemctl stop "${SERVICE}" 28 | sleep 2 29 | systemctl start "${SERVICE}" 30 | sleep 2 31 | if ! systemctl is-active --quiet "${SERVICE}"; then 32 | exit 1 33 | fi 34 | else 35 | systemctl --user daemon-reload 36 | sleep 2 37 | systemctl --user stop "${SERVICE}" 38 | sleep 2 39 | systemctl --user start "${SERVICE}" 40 | sleep 2 41 | if ! systemctl is-active --quiet "${SERVICE}"; then 42 | exit 1 43 | fi 44 | fi 45 | fi 46 | 47 | if [ "$ACTION" == "stop" ]; then 48 | if [ "$ROOT" == "true" ]; then 49 | systemctl stop "${SERVICE}" && rm -rf /etc/systemd/system/"${SERVICE}" 50 | else 51 | systemctl --user stop "${SERVICE}" && rm -rf /etc/systemd/system/"${SERVICE}" 52 | fi 53 | fi 54 | -------------------------------------------------------------------------------- /pkg/engine/ansible.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "context" 5 | "time" 6 | 7 | "github.com/containers/podman/v4/pkg/bindings/containers" 8 | "github.com/containers/podman/v4/pkg/specgen" 9 | "github.com/go-git/go-git/v5/plumbing" 10 | "github.com/go-git/go-git/v5/plumbing/object" 11 | "github.com/opencontainers/runtime-spec/specs-go" 12 | ) 13 | 14 | const ansibleMethod = "ansible" 15 | 16 | // Ansible to place and run ansible playbooks 17 | type Ansible struct { 18 | CommonMethod `mapstructure:",squash"` 19 | // SshDirectory for ansible to connect to host 20 | SshDirectory string `mapstructure:"sshDirectory"` 21 | } 22 | 23 | func (ans *Ansible) GetKind() string { 24 | return ansibleMethod 25 | } 26 | 27 | func (ans *Ansible) Process(ctx, conn context.Context, skew int) { 28 | time.Sleep(time.Duration(skew) * time.Millisecond) 29 | target := ans.GetTarget() 30 | target.mu.Lock() 31 | defer target.mu.Unlock() 32 | 33 | tag := []string{"yaml", "yml"} 34 | if ans.initialRun { 35 | err := getRepo(target) 36 | if err != nil { 37 | logger.Errorf("Failed to clone repository %s: %v", target.url, err) 38 | return 39 | } 40 | 41 | err = zeroToCurrent(ctx, conn, ans, target, &tag) 42 | if err != nil { 43 | logger.Errorf("Error moving to current: %v", err) 44 | return 45 | } 46 | } 47 | 48 | err := currentToLatest(ctx, conn, ans, target, &tag) 49 | if err != nil { 50 | logger.Errorf("Error moving current to latest: %v", err) 51 | return 52 | } 53 | 54 | ans.initialRun = false 55 | } 56 | 57 | func (ans *Ansible) MethodEngine(ctx context.Context, conn context.Context, change *object.Change, path string) error { 58 | return ans.ansiblePodman(ctx, conn, path) 59 | } 60 | 61 | func (ans *Ansible) Apply(ctx, conn context.Context, currentState, desiredState plumbing.Hash, tags *[]string) error { 62 | changeMap, err := applyChanges(ctx, ans.GetTarget(), ans.GetTargetPath(), ans.Glob, currentState, desiredState, tags) 63 | if err != nil { 64 | return err 65 | } 66 | if err := runChanges(ctx, conn, ans, changeMap); err != nil { 67 | return err 68 | } 69 | return nil 70 | } 71 | 72 | func (ans *Ansible) ansiblePodman(ctx, conn context.Context, path string) error { 73 | // TODO: add logic to remove 74 | if path == deleteFile { 75 | return nil 76 | } 77 | logger.Infof("Deploying Ansible playbook %s", path) 78 | 79 | copyFile := ("/opt/" + path) 80 | sshImage := "quay.io/fetchit/fetchit-ansible:latest" 81 | 82 | logger.Infof("Identifying if fetchit-ansible image exists locally") 83 | if err := detectOrFetchImage(conn, sshImage, true); err != nil { 84 | return err 85 | } 86 | 87 | s := specgen.NewSpecGenerator(sshImage, false) 88 | s.Name = "ansible" + "-" + ans.Name 89 | s.Privileged = true 90 | s.PidNS = specgen.Namespace{ 91 | NSMode: "host", 92 | Value: "", 93 | } 94 | 95 | // TODO: Remove rcook entries 96 | s.Command = []string{"sh", "-c", "/usr/bin/ansible-playbook -e ansible_connection=ssh " + copyFile} 97 | s.Mounts = []specs.Mount{{Source: ans.SshDirectory, Destination: "/root/.ssh", Type: "bind", Options: []string{"rw"}}} 98 | s.Volumes = []*specgen.NamedVolume{{Name: fetchitVolume, Dest: "/opt", Options: []string{"ro"}}} 99 | s.NetNS = specgen.Namespace{ 100 | NSMode: "host", 101 | Value: "", 102 | } 103 | createResponse, err := containers.CreateWithSpec(conn, s, nil) 104 | if err != nil { 105 | return err 106 | } 107 | logger.Infof("Container created.") 108 | if err := containers.Start(conn, createResponse.ID, nil); err != nil { 109 | return err 110 | } 111 | // Wait for the container to exit 112 | err = waitAndRemoveContainer(conn, createResponse.ID) 113 | if err != nil { 114 | return err 115 | } 116 | logger.Infof("Container started....Requeuing") 117 | return nil 118 | } 119 | -------------------------------------------------------------------------------- /pkg/engine/apply.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "context" 5 | "crypto/sha1" 6 | "crypto/x509" 7 | "encoding/hex" 8 | "errors" 9 | "fmt" 10 | "os" 11 | "path/filepath" 12 | "strings" 13 | 14 | "github.com/containers/fetchit/pkg/engine/utils" 15 | "github.com/go-git/go-git/v5" 16 | "github.com/go-git/go-git/v5/config" 17 | "github.com/go-git/go-git/v5/plumbing" 18 | "github.com/go-git/go-git/v5/plumbing/object" 19 | githttp "github.com/go-git/go-git/v5/plumbing/transport/http" 20 | "github.com/go-git/go-git/v5/plumbing/transport/ssh" 21 | "github.com/gobwas/glob" 22 | gitsign "github.com/sigstore/gitsign/pkg/git" 23 | gitsignrekor "github.com/sigstore/gitsign/pkg/rekor" 24 | rekorclient "github.com/sigstore/rekor/pkg/client" 25 | ) 26 | 27 | const ( 28 | defaultRekorURL = "https://rekor.sigstore.dev" 29 | hashReportLen = 9 30 | ) 31 | 32 | func applyChanges(ctx context.Context, target *Target, targetPath string, globPattern *string, currentState, desiredState plumbing.Hash, tags *[]string) (map[*object.Change]string, error) { 33 | if desiredState.IsZero() { 34 | return nil, errors.New("Cannot run Apply if desired state is empty") 35 | } 36 | directory := getDirectory(target) 37 | 38 | currentTree, err := getSubTreeFromHash(directory, currentState, targetPath) 39 | if err != nil { 40 | return nil, utils.WrapErr(err, "Error getting tree from hash %s", currentState) 41 | } 42 | 43 | desiredTree, err := getSubTreeFromHash(directory, desiredState, targetPath) 44 | if err != nil { 45 | return nil, utils.WrapErr(err, "Error getting tree from hash %s", desiredState) 46 | } 47 | 48 | changeMap, err := getFilteredChangeMap(directory, targetPath, globPattern, currentTree, desiredTree, tags) 49 | if err != nil { 50 | return nil, utils.WrapErr(err, "Error getting filtered change map from %s to %s", currentState, desiredState) 51 | } 52 | 53 | return changeMap, nil 54 | } 55 | 56 | //getLatest will get the head of the branch in the repository specified by the target's url 57 | func getLatest(target *Target) (plumbing.Hash, error) { 58 | ctx := context.Background() 59 | directory := getDirectory(target) 60 | 61 | repo, err := git.PlainOpen(directory) 62 | if err != nil { 63 | return plumbing.Hash{}, utils.WrapErr(err, "Error opening repository %s to fetch latest commit", directory) 64 | } 65 | if target.envSecret != "" { 66 | logger.Infof("Using the envSecret %s", target.envSecret) 67 | target.pat = os.Getenv(target.envSecret) 68 | } 69 | if target.pat != "" { 70 | target.username = "fetchit" 71 | target.password = target.pat 72 | } 73 | 74 | refSpec := config.RefSpec(fmt.Sprintf("+refs/heads/%s:refs/heads/%s", target.branch, target.branch)) 75 | 76 | // default to using existing http method 77 | fOptions := &git.FetchOptions{ 78 | RemoteName: "", 79 | RefSpecs: []config.RefSpec{refSpec, "HEAD:refs/heads/HEAD"}, 80 | Depth: 0, 81 | Auth: &githttp.BasicAuth{ 82 | Username: target.username, 83 | Password: target.password, 84 | }, 85 | Progress: nil, 86 | Tags: 0, 87 | Force: true, 88 | InsecureSkipTLS: false, 89 | CABundle: []byte{}, 90 | } 91 | // if using ssh, change auth to use ssh key 92 | if target.ssh { 93 | logger.Infof("git clone %s using SSH key %s ", target.url, target.sshKey) 94 | authValue, err := ssh.NewPublicKeysFromFile("git", target.sshKey, target.password) 95 | if err != nil { 96 | logger.Infof("generate publickeys failed: %s", err.Error()) 97 | return plumbing.Hash{}, err 98 | } 99 | fOptions.Auth = authValue 100 | } 101 | if err = repo.Fetch(fOptions); err != nil && err != git.NoErrAlreadyUpToDate && !target.disconnected { 102 | return plumbing.Hash{}, utils.WrapErr(err, "Error fetching branch %s from remote repository %s", target.branch, target.url) 103 | } 104 | 105 | branch, err := repo.Reference(plumbing.ReferenceName(fmt.Sprintf("refs/heads/%s", target.branch)), false) 106 | if err != nil { 107 | return plumbing.Hash{}, utils.WrapErr(err, "Error getting reference to branch %s", target.branch) 108 | } 109 | 110 | wt, err := repo.Worktree() 111 | if err != nil { 112 | return plumbing.Hash{}, utils.WrapErr(err, "Error getting reference to worktree for repository", directory) 113 | } 114 | 115 | hashStr := branch.Hash().String()[:hashReportLen] 116 | if err := wt.Checkout(&git.CheckoutOptions{Hash: branch.Hash()}); err != nil { 117 | return plumbing.Hash{}, utils.WrapErr(err, "Error checking out %s on branch %s", hashStr, target.branch) 118 | } 119 | 120 | if target.gitsignVerify { 121 | commit, err := repo.CommitObject(branch.Hash()) 122 | if err != nil { 123 | return plumbing.Hash{}, utils.WrapErr(err, "Error getting verified commit at hash %s from repository %s", hashStr, directory) 124 | } 125 | if err := VerifyGitsign(ctx, commit, hashStr, directory, target.gitsignRekorURL); err != nil { 126 | return plumbing.Hash{}, utils.WrapErr(err, "Requested verified commit signatures, but commit %s from repository %s failed verification", hashStr, directory) 127 | } 128 | } 129 | return branch.Hash(), err 130 | } 131 | 132 | // VerifyGitsign verifies any commit signed using sigstore/gitsign & rekor 133 | func VerifyGitsign(ctx context.Context, commit *object.Commit, hash, repo, url string) error { 134 | if commit.PGPSignature == "" { 135 | return fmt.Errorf("Requested verified commit signatures, but commit %s from repository %s has no PGPSignature", hash, repo) 136 | } 137 | // Extract signature from commit 138 | pgpsig := commit.PGPSignature + "\n" 139 | r := strings.NewReader(pgpsig) 140 | sig := make([]byte, len(pgpsig)) 141 | if _, err := r.Read(sig); err != nil { 142 | return utils.WrapErr(err, "Error reading signature from commit %s", hash) 143 | } 144 | // Extract everything else from commit 145 | d := &plumbing.MemoryObject{} 146 | if err := commit.EncodeWithoutSignature(d); err != nil { 147 | return utils.WrapErr(err, "Error decoding data from commit %s", hash) 148 | } 149 | er, err := d.Reader() 150 | if err != nil { 151 | return utils.WrapErr(err, "Error configuring data reader from commit %s", hash) 152 | } 153 | data := make([]byte, d.Size()) 154 | if _, err = er.Read(data); err != nil { 155 | return utils.WrapErr(err, "Error reading data from commit %s", hash) 156 | } 157 | 158 | // Rekor client 159 | rekorURL := url 160 | if rekorURL == "" { 161 | rekorURL = defaultRekorURL 162 | } 163 | client, err := gitsignrekor.New(rekorURL, rekorclient.WithUserAgent("gitsign")) 164 | if err != nil { 165 | return utils.WrapErr(err, "Error obtaining rekor client") 166 | } 167 | summary, err := gitsign.Verify(ctx, client, data, sig, true) 168 | if err != nil { 169 | if summary != nil && summary.Cert != nil { 170 | logger.Infof("Bad Signature: GNUPG: %s %s", certHexFingerprint(summary.Cert), summary.Cert.Subject.String()) 171 | } 172 | return utils.WrapErr(err, "Failed to verify signature") 173 | } 174 | logger.Infof("Validated Git signature: GNUPG: %s SUBJECT/ISSUER: %s %s", certHexFingerprint(summary.Cert), summary.Cert.Subject.String(), summary.Cert.Issuer) 175 | logger.Infof("Validated Rekor entry: %d From: %s", summary.LogEntry.LogIndex, summary.Cert.EmailAddresses) 176 | return nil 177 | } 178 | 179 | // borrowed from sigstore/gitsign/internal/git 180 | // certHexFingerprint calculates the hex SHA1 fingerprint of a certificate. 181 | func certHexFingerprint(cert *x509.Certificate) string { 182 | if len(cert.Raw) == 0 { 183 | return "" 184 | } 185 | 186 | fpr := sha1.Sum(cert.Raw) 187 | return hex.EncodeToString(fpr[:]) 188 | } 189 | 190 | func getCurrent(target *Target, methodType, methodName string) (plumbing.Hash, error) { 191 | directory := getDirectory(target) 192 | tagName := fmt.Sprintf("current-%s-%s", methodType, methodName) 193 | 194 | repo, err := git.PlainOpen(directory) 195 | if err != nil { 196 | return plumbing.Hash{}, utils.WrapErr(err, "Error opening repository %s to fetch current commit", directory) 197 | } 198 | 199 | ref, err := repo.Tag(tagName) 200 | if err != nil { 201 | if err == git.ErrTagNotFound { 202 | return plumbing.Hash{}, nil 203 | } 204 | return plumbing.Hash{}, utils.WrapErr(err, "Error getting reference to current tag") 205 | } 206 | 207 | return ref.Hash(), err 208 | } 209 | 210 | func updateCurrent(ctx context.Context, target *Target, newCurrent plumbing.Hash, methodType, methodName string) error { 211 | directory := getDirectory(target) 212 | tagName := fmt.Sprintf("current-%s-%s", methodType, methodName) 213 | 214 | repo, err := git.PlainOpen(directory) 215 | if err != nil { 216 | return utils.WrapErr(err, "Error opening repository %s to update current commit", directory) 217 | } 218 | 219 | err = repo.DeleteTag(tagName) 220 | if err != nil && err != git.ErrTagNotFound { 221 | return utils.WrapErr(err, "Error deleting old current tag") 222 | } 223 | 224 | if _, err := repo.CreateTag(tagName, newCurrent, nil); err != nil { 225 | return utils.WrapErr(err, "Error creating new current tag with hash %s", newCurrent) 226 | } 227 | 228 | return nil 229 | } 230 | 231 | func getSubTreeFromHash(directory string, hash plumbing.Hash, targetPath string) (*object.Tree, error) { 232 | if hash.IsZero() { 233 | return &object.Tree{}, nil 234 | } 235 | 236 | repo, err := git.PlainOpen(directory) 237 | if err != nil { 238 | return nil, utils.WrapErr(err, "Error opening repository %s to fetch sub tree from commit", directory) 239 | } 240 | 241 | commit, err := repo.CommitObject(hash) 242 | if err != nil { 243 | return nil, utils.WrapErr(err, "Error getting commit at hash %s from repository %s", hash, directory) 244 | } 245 | 246 | tree, err := commit.Tree() 247 | if err != nil { 248 | return nil, utils.WrapErr(err, "Error getting tree from commit at hash %s from repository %s", hash, directory) 249 | } 250 | 251 | subTree, err := tree.Tree(targetPath) 252 | if err != nil { 253 | return nil, utils.WrapErr(err, "Error getting sub tree at %s from commit at %s from repository %s", targetPath, hash, directory) 254 | } 255 | 256 | return subTree, nil 257 | } 258 | 259 | func getFilteredChangeMap( 260 | directory, 261 | targetPath string, 262 | globPattern *string, 263 | currentTree, 264 | desiredTree *object.Tree, 265 | tags *[]string, 266 | ) (map[*object.Change]string, error) { 267 | 268 | changes, err := currentTree.Diff(desiredTree) 269 | if err != nil { 270 | return nil, utils.WrapErr(err, "Error getting diff between current and latest", targetPath) 271 | } 272 | 273 | var g glob.Glob 274 | if globPattern == nil { 275 | g, err = glob.Compile("**") 276 | if err != nil { 277 | return nil, utils.WrapErr(err, "Error compiling glob for pattern %s", globPattern) 278 | } 279 | } else { 280 | g, err = glob.Compile(*globPattern) 281 | if err != nil { 282 | return nil, utils.WrapErr(err, "Error compiling glob for pattern %s", globPattern) 283 | } 284 | } 285 | 286 | changeMap := make(map[*object.Change]string) 287 | for _, change := range changes { 288 | if change.To.Name != "" && checkTag(tags, change.To.Name) && g.Match(change.To.Name) { 289 | path := filepath.Join(directory, targetPath, change.To.Name) 290 | changeMap[change] = path 291 | } else if change.From.Name != "" && checkTag(tags, change.From.Name) && g.Match(change.From.Name) { 292 | changeMap[change] = deleteFile 293 | } 294 | } 295 | 296 | return changeMap, nil 297 | } 298 | 299 | func checkTag(tags *[]string, name string) bool { 300 | if tags == nil { 301 | return true 302 | } 303 | for _, suffix := range *tags { 304 | if strings.HasSuffix(name, suffix) { 305 | return true 306 | } 307 | } 308 | return false 309 | } 310 | 311 | func getChangeString(change *object.Change) (*string, error) { 312 | if change != nil { 313 | from, _, err := change.Files() 314 | if err != nil { 315 | return nil, err 316 | } 317 | if from != nil { 318 | s, err := from.Contents() 319 | if err != nil { 320 | return nil, err 321 | } 322 | return &s, nil 323 | } 324 | } 325 | return nil, nil 326 | } 327 | -------------------------------------------------------------------------------- /pkg/engine/clean.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "context" 5 | "time" 6 | 7 | "github.com/containers/fetchit/pkg/engine/utils" 8 | "github.com/containers/podman/v4/pkg/bindings/system" 9 | "github.com/go-git/go-git/v5/plumbing" 10 | "github.com/go-git/go-git/v5/plumbing/object" 11 | ) 12 | 13 | const pruneMethod = "prune" 14 | 15 | // Prune configures targets to run a podman system prune periodically 16 | type Prune struct { 17 | CommonMethod `mapstructure:",squash"` 18 | Volumes bool `mapstructure:"volumes"` 19 | All bool `mapstructure:"all"` 20 | } 21 | 22 | func (p *Prune) GetKind() string { 23 | return pruneMethod 24 | } 25 | 26 | func (p *Prune) GetName() string { 27 | return pruneMethod 28 | } 29 | 30 | func (p *Prune) Process(ctx, conn context.Context, skew int) { 31 | target := p.GetTarget() 32 | time.Sleep(time.Duration(skew) * time.Millisecond) 33 | target.mu.Lock() 34 | defer target.mu.Unlock() 35 | // Nothing to do with certain file we're just collecting garbage so can call the prunePodman method straight from here 36 | opts := system.PruneOptions{ 37 | All: &p.All, 38 | Volumes: &p.Volumes, 39 | } 40 | 41 | err := p.prunePodman(ctx, conn, opts) 42 | if err != nil { 43 | logger.Debugf("Repository: %s Method: %s encountered error: %v, resetting...", target.url, pruneMethod, err) 44 | } 45 | 46 | } 47 | 48 | func (p *Prune) MethodEngine(ctx, conn context.Context, change *object.Change, path string) error { 49 | return nil 50 | } 51 | 52 | func (p *Prune) Apply(ctx, conn context.Context, currentState, desiredState plumbing.Hash, tags *[]string) error { 53 | return nil 54 | } 55 | 56 | func (p *Prune) prunePodman(ctx, conn context.Context, opts system.PruneOptions) error { 57 | logger.Info("Pruning system") 58 | report, err := system.Prune(conn, &opts) 59 | if err != nil { 60 | return utils.WrapErr(err, "Error pruning system") 61 | } 62 | for _, report := range report.ContainerPruneReports { 63 | logger.Infof("Pruned container of size %v with id: %s", report.Size, report.Id) 64 | } 65 | 66 | for _, report := range report.ImagePruneReports { 67 | logger.Infof("Pruned image of size %v with id: %s", report.Size, report.Id) 68 | } 69 | 70 | for _, report := range report.PodPruneReport { 71 | logger.Infof("Pruned pod with id: %s", report.Id) 72 | } 73 | 74 | for _, report := range report.VolumePruneReports { 75 | logger.Infof("Pruned volume of size %v with id: %s", report.Size, report.Id) 76 | } 77 | 78 | logger.Infof("Reclaimed %vB", report.ReclaimedSpace) 79 | 80 | return nil 81 | } 82 | -------------------------------------------------------------------------------- /pkg/engine/common.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "path" 7 | "path/filepath" 8 | "strings" 9 | 10 | "github.com/go-git/go-git/v5/plumbing" 11 | "github.com/go-git/go-git/v5/plumbing/object" 12 | ) 13 | 14 | type CommonMethod struct { 15 | // Name must be unique within target method 16 | Name string `mapstructure:"name"` 17 | // Schedule is how often to check for git updates and/or restart the fetchit service 18 | // Must be valid cron expression 19 | Schedule string `mapstructure:"schedule"` 20 | // Number of seconds to skew the schedule by 21 | Skew *int `mapstructure:"skew"` 22 | // Where in the git repository to fetch a file or directory (to fetch all files in directory) 23 | TargetPath string `mapstructure:"targetPath"` 24 | // A glob to pattern match files in the target path directory 25 | Glob *string `mapstructure:"glob"` 26 | // initialRun is set by fetchit 27 | initialRun bool 28 | target *Target 29 | } 30 | 31 | func (m *CommonMethod) GetName() string { 32 | return m.Name 33 | } 34 | 35 | func (m *CommonMethod) SchedInfo() SchedInfo { 36 | return SchedInfo{ 37 | schedule: m.Schedule, 38 | skew: m.Skew, 39 | } 40 | } 41 | 42 | func (m *CommonMethod) GetTargetPath() string { 43 | return m.TargetPath 44 | } 45 | 46 | func (m *CommonMethod) GetTarget() *Target { 47 | return m.target 48 | } 49 | 50 | func zeroToCurrent(ctx, conn context.Context, m Method, target *Target, tag *[]string) error { 51 | current, err := getCurrent(target, m.GetKind(), m.GetName()) 52 | if err != nil { 53 | return fmt.Errorf("Failed to get current commit: %v", err) 54 | } 55 | 56 | if current != plumbing.ZeroHash { 57 | err = m.Apply(ctx, conn, plumbing.ZeroHash, current, tag) 58 | if err != nil { 59 | return fmt.Errorf("Failed to apply changes: %v", err) 60 | } 61 | 62 | logger.Infof("Moved %s to commit %s for git target %s", m.GetName(), current.String()[:hashReportLen], target.url) 63 | } 64 | 65 | return nil 66 | } 67 | 68 | func getDirectory(target *Target) string { 69 | trimDir := strings.TrimSuffix(target.url, path.Ext(target.url)) 70 | return filepath.Base(trimDir) 71 | } 72 | 73 | func currentToLatest(ctx, conn context.Context, m Method, target *Target, tag *[]string) error { 74 | directory := getDirectory(target) 75 | if target.disconnected { 76 | if len(target.url) > 0 { 77 | extractZip(target.url) 78 | } else if len(target.device) > 0 { 79 | localDevicePull(directory, target.device, "", false) 80 | } 81 | } 82 | latest, err := getLatest(target) 83 | if err != nil { 84 | return fmt.Errorf("Failed to get latest commit: %v", err) 85 | } 86 | 87 | current, err := getCurrent(target, m.GetKind(), m.GetName()) 88 | if err != nil { 89 | return fmt.Errorf("Failed to get current commit: %v", err) 90 | } 91 | 92 | if latest != current { 93 | if err := m.Apply(ctx, conn, current, latest, tag); err != nil { 94 | return fmt.Errorf("Failed to apply changes: %v", err) 95 | } 96 | updateCurrent(ctx, target, latest, m.GetKind(), m.GetName()) 97 | logger.Infof("Moved %s from %s to %s for git target %s", m.GetName(), current.String()[:hashReportLen], latest, target.url) 98 | } else { 99 | logger.Infof("No changes applied to git target %s this run, %s currently at %s", directory, m.GetKind(), current.String()[:hashReportLen]) 100 | } 101 | 102 | return nil 103 | } 104 | 105 | func runChanges(ctx context.Context, conn context.Context, m Method, changeMap map[*object.Change]string) error { 106 | for change, changePath := range changeMap { 107 | if err := m.MethodEngine(ctx, conn, change, changePath); err != nil { 108 | return err 109 | } 110 | } 111 | return nil 112 | } 113 | -------------------------------------------------------------------------------- /pkg/engine/config.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "fmt" 7 | "io" 8 | "io/ioutil" 9 | "net/http" 10 | "net/url" 11 | "os" 12 | "time" 13 | 14 | "github.com/containers/podman/v4/pkg/bindings" 15 | "github.com/go-git/go-git/v5/plumbing" 16 | "github.com/go-git/go-git/v5/plumbing/object" 17 | ) 18 | 19 | const configFileMethod = "config" 20 | 21 | // ConfigReload configures a target for dynamic loading of fetchit config updates 22 | // $FETCHIT_CONFIG_URL environment variable or a local file with a ConfigReload target 23 | // at ~/.fetchit/config.yaml will inform fetchit to use this target. 24 | // Without this target, fetchit will not watch for config updates. 25 | // At this time, only 1 FetchitConfigReload target can be passed to fetchit 26 | // TODO: Collect multiple from multiple FetchitTargets and merge configs into 1 on disk 27 | type ConfigReload struct { 28 | CommonMethod `mapstructure:",squash"` 29 | ConfigURL string `mapstructure:"configURL"` 30 | Device string `mapstructure:"device"` 31 | ConfigPath string `mapstructure:"configPath"` 32 | GitAuth `mapstructure:",squash"` 33 | } 34 | 35 | func (c *ConfigReload) GetKind() string { 36 | return configFileMethod 37 | } 38 | 39 | func (c *ConfigReload) GetName() string { 40 | return configFileMethod 41 | } 42 | 43 | func (c *ConfigReload) Process(ctx, conn context.Context, skew int) { 44 | time.Sleep(time.Duration(skew) * time.Millisecond) 45 | // configURL in config file will override the environment variable 46 | envURL := os.Getenv("FETCHIT_CONFIG_URL") 47 | // config.URL from target overrides env variable 48 | if c.ConfigURL != "" { 49 | envURL = c.ConfigURL 50 | } 51 | pat := fetchit.pat 52 | if fetchit.envSecret != "" { 53 | pat = os.Getenv(fetchit.envSecret) 54 | } 55 | username := fetchit.username 56 | password := fetchit.password 57 | // If ConfigURL is not populated, warn and leave 58 | if envURL == "" && c.Device == "" { 59 | logger.Debugf("Fetchit ConfigReload found, but neither $FETCHIT_CONFIG_URL on system nor ConfigReload.ConfigURL are set, exiting without updating the config.") 60 | } 61 | // CheckForConfigUpdates downloads & places config file in defaultConfigPath 62 | // if the downloaded config file differs from what's currently on the system. 63 | if envURL != "" { 64 | restart := checkForConfigUpdates(envURL, true, false, pat, username, password) 65 | if !restart { 66 | return 67 | } 68 | logger.Info("Updated config processed, restarting with new targets") 69 | fetchitConfig.Restart() 70 | } else if c.Device != "" { 71 | restart := checkForDisconUpdates(c.Device, c.ConfigPath, true, false) 72 | if !restart { 73 | return 74 | } 75 | logger.Info("Updated config processed, restarting with new targets") 76 | fetchitConfig.Restart() 77 | } 78 | 79 | } 80 | 81 | func (c *ConfigReload) MethodEngine(ctx, conn context.Context, change *object.Change, path string) error { 82 | return nil 83 | } 84 | 85 | func (c *ConfigReload) Apply(ctx, conn context.Context, currentState, desiredState plumbing.Hash, tags *[]string) error { 86 | return nil 87 | } 88 | 89 | // checkForConfigUpdates downloads & places config file 90 | // in defaultConfigPath in fetchit container (/opt/mount/config.yaml). 91 | // This runs with the initial startup as well as with scheduled ConfigReload runs, 92 | // if $FETCHIT_CONFIG_URL is set. 93 | func checkForConfigUpdates(envURL string, existsAlready bool, initial bool, pat, username, password string) bool { 94 | // envURL is either set by user or set to match a configURL in a configReload 95 | if envURL == "" { 96 | return false 97 | } 98 | reset, err := downloadUpdateConfigFile(envURL, existsAlready, initial, pat, username, password) 99 | if err != nil { 100 | logger.Info(err) 101 | } 102 | return reset 103 | } 104 | 105 | // CheckForDisconUpdates identifies if the device is connected and if a cache file exists 106 | func checkForDisconUpdates(device, configPath string, existsAlready bool, initial bool) bool { 107 | ctx := context.Background() 108 | name := "fetchit-config" 109 | cache := "/opt/.cache/" + name 110 | dest := cache + "/" + "config.yaml" 111 | conn, err := bindings.NewConnection(ctx, "unix://run/podman/podman.sock") 112 | if err != nil { 113 | logger.Error("Failed to create connection to podman") 114 | return false 115 | } 116 | // Ensure that the device is present 117 | _, exitCode, err := localDeviceCheck(name, device, "") 118 | if err != nil { 119 | logger.Error("Failed to check device") 120 | return false 121 | } 122 | if exitCode != 0 { 123 | // remove the diff file 124 | err = os.Remove(dest) 125 | logger.Info("Device not present...requeuing") 126 | return false 127 | } else if exitCode == 0 { 128 | if _, err := os.Stat(dest); os.IsNotExist(err) { 129 | // make the cache directory 130 | err = os.MkdirAll(cache, 0755) 131 | copyFile := ("/mnt/" + configPath + " " + dest) 132 | s := generateDeviceSpec(filetransferMethod, "disconnected-", copyFile, device, name) 133 | createResponse, err := createAndStartContainer(conn, s) 134 | if err != nil { 135 | return false 136 | } 137 | // Wait for the container to finish 138 | waitAndRemoveContainer(conn, createResponse.ID) 139 | logger.Info("container created", createResponse.ID) 140 | currentConfigBytes, err := ioutil.ReadFile(defaultConfigPath) 141 | newBytes, err := ioutil.ReadFile(dest) 142 | if err != nil { 143 | logger.Error("Failed to read config file") 144 | } else { 145 | if bytes.Equal(newBytes, currentConfigBytes) { 146 | return false 147 | } else { 148 | // Replace the old config file at defaultConfigPath with the new one from dest and restart 149 | os.WriteFile(defaultConfigBackup, currentConfigBytes, 0600) 150 | os.WriteFile(defaultConfigPath, newBytes, 0600) 151 | logger.Infof("Current config backup placed at %s", defaultConfigBackup) 152 | return true 153 | } 154 | } 155 | } 156 | } 157 | return false 158 | } 159 | 160 | // downloadUpdateConfig returns true if config was updated in fetchit pod 161 | func downloadUpdateConfigFile(urlStr string, existsAlready, initial bool, pat, username, password string) (bool, error) { 162 | _, err := url.Parse(urlStr) 163 | if err != nil { 164 | return false, fmt.Errorf("unable to parse config file url %s: %v", urlStr, err) 165 | } 166 | client := http.Client{ 167 | CheckRedirect: func(r *http.Request, via []*http.Request) error { 168 | r.URL.Opaque = r.URL.Path 169 | return nil 170 | }, 171 | } 172 | req, err := http.NewRequest("GET", urlStr, nil) 173 | if err != nil { 174 | return false, fmt.Errorf("unable to create request: %v", err) 175 | } 176 | if pat != "" { 177 | req.Header.Add("Authorization", "token "+pat) 178 | req.Header.Add("Accept", "application/vnd.github.v3+json") 179 | } 180 | if username != "" && password != "" { 181 | req.SetBasicAuth(username, password) 182 | } 183 | resp, err := client.Do(req) 184 | if err != nil { 185 | return false, err 186 | } 187 | defer resp.Body.Close() 188 | newBytes, err := io.ReadAll(resp.Body) 189 | if err != nil { 190 | return false, fmt.Errorf("error downloading config from %s: %v", err) 191 | } 192 | if newBytes == nil { 193 | // if initial, this is the last resort, newBytes should be populated 194 | // the only way to get here from initial 195 | // is if there is no config file on disk, only a FETCHIT_CONFIG_URL 196 | return false, fmt.Errorf("found empty config at %s, unable to update or populate config", urlStr) 197 | } 198 | if !initial { 199 | currentConfigBytes, err := ioutil.ReadFile(defaultConfigPath) 200 | if err != nil { 201 | logger.Infof("unable to read current config, will try with new downloaded config file: %v", err) 202 | existsAlready = false 203 | } else { 204 | if bytes.Equal(newBytes, currentConfigBytes) { 205 | return false, nil 206 | } 207 | } 208 | 209 | if existsAlready { 210 | if err := os.WriteFile(defaultConfigBackup, currentConfigBytes, 0600); err != nil { 211 | return false, fmt.Errorf("could not copy %s to path %s: %v", defaultConfigPath, defaultConfigBackup, err) 212 | } 213 | logger.Infof("Current config backup placed at %s", defaultConfigBackup) 214 | } 215 | } 216 | if err := os.WriteFile(defaultConfigPath, newBytes, 0600); err != nil { 217 | return false, fmt.Errorf("unable to write new config contents, reverting to old config: %v", err) 218 | } 219 | 220 | logger.Infof("Config updates found from url: %s, will load new targets", urlStr) 221 | return true, nil 222 | } 223 | -------------------------------------------------------------------------------- /pkg/engine/container.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/containers/podman/v4/libpod/define" 7 | "github.com/containers/podman/v4/pkg/bindings/containers" 8 | "github.com/containers/podman/v4/pkg/bindings/images" 9 | "github.com/containers/podman/v4/pkg/domain/entities" 10 | "github.com/containers/podman/v4/pkg/specgen" 11 | "github.com/opencontainers/runtime-spec/specs-go" 12 | ) 13 | 14 | const stopped = define.ContainerStateStopped 15 | 16 | func generateSpec(method, file, copyFile, dest string, name string) *specgen.SpecGenerator { 17 | s := specgen.NewSpecGenerator(fetchitImage, false) 18 | s.Name = method + "-" + name + "-" + file 19 | s.Privileged = true 20 | s.PidNS = specgen.Namespace{ 21 | NSMode: "host", 22 | Value: "", 23 | } 24 | s.Command = []string{"sh", "-c", "rsync -avz" + " " + copyFile} 25 | s.Mounts = []specs.Mount{{Source: dest, Destination: dest, Type: "bind", Options: []string{"rw"}}} 26 | s.Volumes = []*specgen.NamedVolume{{Name: fetchitVolume, Dest: "/opt", Options: []string{"rw"}}} 27 | return s 28 | } 29 | 30 | func generateDeviceSpec(method, file, copyFile, device string, name string) *specgen.SpecGenerator { 31 | s := specgen.NewSpecGenerator(fetchitImage, false) 32 | s.Name = method + "-" + name + "-" + file 33 | s.Privileged = true 34 | s.PidNS = specgen.Namespace{ 35 | NSMode: "host", 36 | Value: "", 37 | } 38 | s.Command = []string{"sh", "-c", "mount" + " " + device + " " + "/mnt/ ; rsync -avz" + " " + copyFile} 39 | s.Volumes = []*specgen.NamedVolume{{Name: fetchitVolume, Dest: "/opt", Options: []string{"rw"}}} 40 | s.Devices = []specs.LinuxDevice{{Path: device}} 41 | return s 42 | } 43 | 44 | func generateDevicePresentSpec(method, file, device string, name string) *specgen.SpecGenerator { 45 | s := specgen.NewSpecGenerator(fetchitImage, false) 46 | s.Name = method + "-" + name + "-" + file + "-" + "device-check" 47 | s.Privileged = true 48 | s.PidNS = specgen.Namespace{ 49 | NSMode: "host", 50 | Value: "", 51 | } 52 | s.Command = []string{"sh", "-c", "if [ ! -b " + device + " ]; then exit 1; fi"} 53 | s.Devices = []specs.LinuxDevice{{Path: device}} 54 | return s 55 | } 56 | 57 | func generateSpecRemove(method, file, pathToRemove, dest, name string) *specgen.SpecGenerator { 58 | s := specgen.NewSpecGenerator(fetchitImage, false) 59 | s.Name = method + "-" + name + "-" + file 60 | s.Privileged = true 61 | s.PidNS = specgen.Namespace{ 62 | NSMode: "host", 63 | Value: "", 64 | } 65 | s.Command = []string{"sh", "-c", "rm " + pathToRemove} 66 | s.Mounts = []specs.Mount{{Source: dest, Destination: dest, Type: "bind", Options: []string{"rw"}}} 67 | s.Volumes = []*specgen.NamedVolume{{Name: fetchitVolume, Dest: "/opt", Options: []string{"ro"}}} 68 | return s 69 | } 70 | 71 | func createAndStartContainer(conn context.Context, s *specgen.SpecGenerator) (entities.ContainerCreateResponse, error) { 72 | createResponse, err := containers.CreateWithSpec(conn, s, nil) 73 | if err != nil { 74 | return createResponse, err 75 | } 76 | 77 | if err := containers.Start(conn, createResponse.ID, nil); err != nil { 78 | return createResponse, err 79 | } 80 | 81 | return createResponse, nil 82 | } 83 | 84 | func waitAndRemoveContainer(conn context.Context, ID string) error { 85 | _, err := containers.Wait(conn, ID, new(containers.WaitOptions).WithCondition([]define.ContainerStatus{stopped})) 86 | if err != nil { 87 | return err 88 | } 89 | 90 | _, err = containers.Remove(conn, ID, new(containers.RemoveOptions).WithForce(true)) 91 | if err != nil { 92 | // There's a podman bug somewhere that's causing this 93 | if err.Error() == "unexpected end of JSON input" { 94 | return nil 95 | } 96 | return err 97 | } 98 | 99 | return nil 100 | } 101 | 102 | func detectOrFetchImage(conn context.Context, imageName string, force bool) error { 103 | present, err := images.Exists(conn, imageName, nil) 104 | if err != nil { 105 | return err 106 | } 107 | 108 | if !present || force { 109 | _, err = images.Pull(conn, imageName, nil) 110 | if err != nil { 111 | return err 112 | } 113 | } 114 | 115 | return nil 116 | } 117 | -------------------------------------------------------------------------------- /pkg/engine/disconnected.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "archive/zip" 5 | "context" 6 | "io" 7 | "net/http" 8 | "os" 9 | "path" 10 | "path/filepath" 11 | "strings" 12 | 13 | "github.com/containers/podman/v4/libpod/define" 14 | "github.com/containers/podman/v4/pkg/bindings" 15 | "github.com/containers/podman/v4/pkg/bindings/containers" 16 | ) 17 | 18 | func extractZip(url string) error { 19 | trimDir := strings.TrimSuffix(url, path.Ext(url)) 20 | directory := filepath.Base(trimDir) 21 | cache := "/opt/.cache/" + directory + "/" 22 | dest := cache + "HEAD" 23 | absPath, err := filepath.Abs(directory) 24 | 25 | data, err := http.Get(url) 26 | if err != nil { 27 | if _, err := os.Stat(dest); err == nil { 28 | // remove the diff file 29 | err = os.Remove(dest) 30 | if err != nil { 31 | logger.Info("Failed to remove file ", dest) 32 | return err 33 | } 34 | } 35 | logger.Info("URL not present...requeuing") 36 | return nil 37 | } else if data.StatusCode == http.StatusOK { 38 | if _, err := os.Stat(dest); os.IsNotExist(err) { 39 | defer data.Body.Close() 40 | // Check the http response code and if not present exit 41 | logger.Infof("loading disconnected archive from %s", url) 42 | // Place the data into the placeholder file 43 | 44 | // Unzip the data from the http response 45 | // Create the destination file 46 | os.MkdirAll(directory, 0755) 47 | 48 | outFile, err := os.Create(absPath + "/" + directory + ".zip") 49 | if err != nil { 50 | logger.Error("Failed creating file ", absPath+"/"+directory+".zip") 51 | return err 52 | } 53 | 54 | // Write the body to file 55 | io.Copy(outFile, data.Body) 56 | 57 | // Unzip the file 58 | r, err := zip.OpenReader(outFile.Name()) 59 | if err != nil { 60 | logger.Infof("error opening zip file: %s", err) 61 | } 62 | for _, f := range r.File { 63 | rc, err := f.Open() 64 | if err != nil { 65 | return err 66 | } 67 | defer rc.Close() 68 | 69 | fpath := filepath.Join(directory, f.Name) 70 | if f.FileInfo().IsDir() { 71 | os.MkdirAll(fpath, f.Mode()) 72 | } else { 73 | var fdir string 74 | if lastIndex := strings.LastIndex(fpath, string(os.PathSeparator)); lastIndex > -1 { 75 | fdir = fpath[:lastIndex] 76 | } 77 | 78 | os.MkdirAll(fdir, f.Mode()) 79 | f, err := os.OpenFile( 80 | fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) 81 | if err != nil { 82 | return err 83 | } 84 | defer f.Close() 85 | 86 | _, err = io.Copy(f, rc) 87 | if err != nil { 88 | return err 89 | } 90 | } 91 | } 92 | err = os.Remove(outFile.Name()) 93 | if err != nil { 94 | logger.Error("Failed removing file ", outFile.Name()) 95 | return err 96 | } 97 | createDiffFile(directory) 98 | return nil 99 | } else { 100 | logger.Info("No changes since last disonnected run...requeuing") 101 | } 102 | } 103 | return nil 104 | } 105 | 106 | func localDevicePull(name, device, trimDir string, image bool) (id string, err error) { 107 | // Need to use the filetransfer method to populate the directory from the localPath 108 | ctx := context.Background() 109 | conn, err := bindings.NewConnection(ctx, "unix://run/podman/podman.sock") 110 | if err != nil { 111 | logger.Error("Failed to create connection to podman") 112 | return "", err 113 | } 114 | // Ensure that the device is present 115 | _, exitCode, err := localDeviceCheck(name, device, trimDir) 116 | if err != nil { 117 | logger.Error("Failed to check device") 118 | return "", err 119 | } 120 | if exitCode != 0 { 121 | // remove the diff file 122 | cache := "/opt/.cache/" + name + "/" 123 | dest := cache + "/" + "HEAD" 124 | err = os.Remove(dest) 125 | logger.Info("Device not present...requeuing") 126 | return "", nil 127 | } 128 | if exitCode == 0 { 129 | // List currently running containers to ensure we don't create a duplicate 130 | containerName := string(filetransferMethod + "-" + name + "-" + "disconnected" + "-" + trimDir) 131 | inspectData, err := containers.Inspect(conn, containerName, new(containers.InspectOptions).WithSize(true)) 132 | if err == nil || inspectData == nil { 133 | logger.Error("The container already exists..requeuing") 134 | return "", err 135 | } 136 | 137 | copyFile := ("/mnt/" + name + " " + "/opt" + "/") 138 | s := generateDeviceSpec(filetransferMethod, "disconnected"+trimDir, copyFile, device, name) 139 | createResponse, err := createAndStartContainer(conn, s) 140 | if err != nil { 141 | return "", err 142 | } 143 | // Wait for the container to finish 144 | waitAndRemoveContainer(conn, createResponse.ID) 145 | if !image { 146 | createDiffFile(name) 147 | } 148 | return createResponse.ID, nil 149 | } 150 | return "", nil 151 | } 152 | 153 | // This function is more of a health check to check if the device is present. If the device 154 | // doesn't exist, it will return an error. 155 | func localDeviceCheck(name, device, trimDir string) (id string, exitcode int32, err error) { 156 | // Need to use the filetransfer method to populate the directory from the localPath 157 | ctx := context.Background() 158 | conn, err := bindings.NewConnection(ctx, "unix://run/podman/podman.sock") 159 | if err != nil { 160 | logger.Error("Failed to create connection to podman") 161 | return "", 0, err 162 | } 163 | // List currently running containers to ensure we don't create a duplicate 164 | containerName := string(filetransferMethod + "-" + name + "-" + "disconnected" + trimDir) 165 | inspectData, err := containers.Inspect(conn, containerName, new(containers.InspectOptions).WithSize(true)) 166 | if err == nil || inspectData == nil { 167 | logger.Error("The container already exists..requeuing") 168 | return "", 0, err 169 | } 170 | 171 | s := generateDevicePresentSpec(filetransferMethod, "disconnected"+trimDir, device, name) 172 | createResponse, err := createAndStartContainer(conn, s) 173 | if err != nil { 174 | return "", 0, err 175 | } 176 | 177 | // Wait for the container to finish 178 | exitCode, err := containers.Wait(conn, createResponse.ID, new(containers.WaitOptions).WithCondition([]define.ContainerStatus{stopped})) 179 | if err != nil { 180 | return "", exitCode, err 181 | } 182 | 183 | _, err = containers.Remove(conn, createResponse.ID, new(containers.RemoveOptions).WithForce(true)) 184 | if err != nil { 185 | // There's a podman bug somewhere that's causing this 186 | if err.Error() == "unexpected end of JSON input" { 187 | return "", exitCode, nil 188 | } 189 | return "", exitCode, err 190 | } 191 | 192 | return createResponse.ID, exitCode, nil 193 | } 194 | 195 | func createDiffFile(name string) error { 196 | cache := "/opt/.cache/" + name + "/" 197 | os.MkdirAll(cache, os.ModePerm) 198 | // Copy the file to the cache directory 199 | src := "/opt/" + name + "/" + ".git/logs/HEAD" 200 | dest := cache + "/" + "HEAD" 201 | // Read the src file 202 | srcFile, err := os.Open(src) 203 | if err != nil { 204 | logger.Error("Failed to open file ", src) 205 | return err 206 | } 207 | destination, err := os.Create(dest) 208 | if err != nil { 209 | logger.Error("Failed to create file ", dest) 210 | return err 211 | } 212 | defer destination.Close() 213 | _, err = io.Copy(destination, srcFile) 214 | if err != nil { 215 | logger.Error("Failed to copy file ", src) 216 | return err 217 | } 218 | return nil 219 | } 220 | -------------------------------------------------------------------------------- /pkg/engine/fetchit.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "math/rand" 7 | "os" 8 | "path/filepath" 9 | "time" 10 | 11 | "github.com/containers/podman/v4/pkg/bindings" 12 | "github.com/go-co-op/gocron" 13 | "github.com/go-git/go-git/v5" 14 | "github.com/go-git/go-git/v5/plumbing" 15 | githttp "github.com/go-git/go-git/v5/plumbing/transport/http" 16 | "github.com/go-git/go-git/v5/plumbing/transport/ssh" 17 | "github.com/spf13/cobra" 18 | "github.com/spf13/viper" 19 | ) 20 | 21 | const ( 22 | fetchitService = "fetchit" 23 | fetchitVolume = "fetchit-volume" 24 | fetchitImage = "quay.io/fetchit/fetchit:latest" 25 | deleteFile = "delete" 26 | ) 27 | 28 | var ( 29 | defaultConfigPath = filepath.Join("/opt", "mount", "config.yaml") 30 | defaultConfigBackup = filepath.Join("/opt", "mount", "config-backup.yaml") 31 | 32 | fetchitConfig *FetchitConfig 33 | fetchit *Fetchit 34 | ) 35 | 36 | type Fetchit struct { 37 | // conn holds podman client 38 | conn context.Context 39 | volume string 40 | ssh bool 41 | sshKey string 42 | username string 43 | password string 44 | pat string 45 | envSecret string 46 | restartFetchit bool 47 | scheduler *gocron.Scheduler 48 | methodTargetScheds map[Method]SchedInfo 49 | allMethodTypes map[string]struct{} 50 | } 51 | 52 | func newFetchit() *Fetchit { 53 | return &Fetchit{ 54 | methodTargetScheds: make(map[Method]SchedInfo), 55 | allMethodTypes: make(map[string]struct{}), 56 | } 57 | } 58 | 59 | func newFetchitConfig() *FetchitConfig { 60 | return &FetchitConfig{ 61 | TargetConfigs: []*TargetConfig{}, 62 | } 63 | } 64 | 65 | // fetchitCmd represents the base command when called without any subcommands 66 | var fetchitCmd = &cobra.Command{ 67 | Version: "0.0.0", 68 | Use: fetchitService, 69 | Short: "a tool to schedule gitOps workflows", 70 | Long: "Fetchit is a tool to schedule gitOps workflows based on a given configuration file", 71 | Run: func(cmd *cobra.Command, args []string) { 72 | cmd.Help() 73 | }, 74 | } 75 | 76 | // Execute adds all child commands to the root command and sets flags 77 | // appropriately. This is called by main.main(). 78 | func Execute() { 79 | cobra.CheckErr(fetchitCmd.Execute()) 80 | } 81 | 82 | // restart fetches new targets from an updated config 83 | // new targets will be added, stale removed, and existing 84 | // will set last commit as last known. 85 | func (fc *FetchitConfig) Restart() { 86 | for mt := range fetchit.allMethodTypes { 87 | fetchit.scheduler.RemoveByTags(mt) 88 | } 89 | fetchit.scheduler.Clear() 90 | fetchit = fc.InitConfig(false) 91 | fetchit.RunTargets() 92 | } 93 | 94 | func readConfig(v *viper.Viper) (*FetchitConfig, bool, error) { 95 | config := newFetchitConfig() 96 | configDir := filepath.Dir(defaultConfigPath) 97 | configName := filepath.Base(defaultConfigPath) 98 | v.AddConfigPath(configDir) 99 | v.SetConfigName(configName) 100 | v.SetConfigType("yaml") 101 | 102 | if err := v.ReadInConfig(); err == nil { 103 | if err := v.Unmarshal(&config); err != nil { 104 | logger.Info("Error with unmarshal of existing config file: %v", err) 105 | return nil, false, err 106 | } 107 | } 108 | return config, true, nil 109 | } 110 | 111 | func (fc *FetchitConfig) populateFetchit(config *FetchitConfig) *Fetchit { 112 | fetchit = newFetchit() 113 | ctx := context.Background() 114 | if fc.conn == nil { 115 | // TODO: socket directory same for all platforms? 116 | // sock_dir := os.Getenv("XDG_RUNTIME_DIR") 117 | // socket := "unix:" + sock_dir + "/podman/podman.sock" 118 | conn, err := bindings.NewConnection(ctx, "unix://run/podman/podman.sock") 119 | if err != nil || conn == nil { 120 | cobra.CheckErr(fmt.Errorf("error establishing connection to podman.sock: %v", err)) 121 | } 122 | fc.conn = conn 123 | } 124 | fetchit.conn = fc.conn 125 | 126 | if err := detectOrFetchImage(fc.conn, fetchitImage, false); err != nil { 127 | cobra.CheckErr(err) 128 | } 129 | 130 | // look for a ConfigURL, only find the first 131 | // TODO: add logic to merge multiple configs 132 | if config.ConfigReload != nil { 133 | if config.ConfigReload.ConfigURL != "" || config.ConfigReload.Device != "" { 134 | // reset URL if necessary 135 | // ConfigURL set in config file overrides env variable 136 | // If the same, this is no change, if diff then the new config has updated the configURL 137 | os.Setenv("FETCHIT_CONFIG_URL", config.ConfigReload.ConfigURL) 138 | // Convert configReload to a proper target for processing 139 | reload := &TargetConfig{ 140 | configReload: config.ConfigReload, 141 | } 142 | config.TargetConfigs = append(config.TargetConfigs, reload) 143 | } 144 | } 145 | 146 | // Check for GitAuth field 147 | if config.GitAuth != nil { 148 | // Check for SSH usage 149 | if config.GitAuth.SSH { 150 | if err := os.Setenv("SSH_KNOWN_HOSTS", "/opt/mount/.ssh/known_hosts"); err != nil { 151 | cobra.CheckErr(err) 152 | } 153 | keyPath := defaultSSHKey 154 | // Check for unique ssh key file 155 | if config.GitAuth.SSHKeyFile != "" { 156 | keyPath = filepath.Join("/opt", "mount", ".ssh", config.GitAuth.SSHKeyFile) 157 | } 158 | if err := checkForPrivateKey(keyPath); err != nil { 159 | cobra.CheckErr(err) 160 | } 161 | fetchit.ssh = true 162 | fetchit.sshKey = keyPath 163 | } 164 | fetchit.username = config.GitAuth.Username 165 | fetchit.password = config.GitAuth.Password 166 | fetchit.pat = config.GitAuth.PAT 167 | fetchit.envSecret = config.GitAuth.EnvSecret 168 | } 169 | 170 | if config.Prune != nil { 171 | prune := &TargetConfig{ 172 | prune: config.Prune, 173 | } 174 | config.TargetConfigs = append(config.TargetConfigs, prune) 175 | } 176 | if config.Images != nil { 177 | for _, i := range config.Images { 178 | imageLoad := &TargetConfig{ 179 | image: i, 180 | } 181 | config.TargetConfigs = append(config.TargetConfigs, imageLoad) 182 | } 183 | } 184 | if config.PodmanAutoUpdate != nil { 185 | sysds := config.PodmanAutoUpdate.AutoUpdateSystemd() 186 | autoUp := &TargetConfig{ 187 | Systemd: sysds, 188 | } 189 | config.TargetConfigs = append(config.TargetConfigs, autoUp) 190 | } 191 | 192 | fc.TargetConfigs = config.TargetConfigs 193 | if fc.scheduler == nil { 194 | fc.scheduler = gocron.NewScheduler(time.UTC) 195 | } 196 | fetchit.scheduler = fc.scheduler 197 | return getMethodTargetScheds(fc.TargetConfigs, fetchit) 198 | } 199 | 200 | // This location will be checked first. This is from a `-v /path/to/config.yaml:/opt/mount/config.yaml`, 201 | // If not initial, this may be overwritten with what is currently in FETCHIT_CONFIG_URL 202 | func isLocalConfig(v *viper.Viper) (*FetchitConfig, bool, error) { 203 | if _, err := os.Stat(defaultConfigPath); err != nil { 204 | logger.Infof("Local config file not found: %v", err) 205 | return nil, false, err 206 | } 207 | return readConfig(v) 208 | } 209 | 210 | // Initconfig reads in config file and env variables if set. 211 | func (fc *FetchitConfig) InitConfig(initial bool) *Fetchit { 212 | InitLogger() 213 | defer logger.Sync() 214 | v := viper.New() 215 | var err error 216 | var isLocal, exists bool 217 | var config *FetchitConfig 218 | envURL := os.Getenv("FETCHIT_CONFIG_URL") 219 | 220 | // user will pass path on local system, but it must be mounted at the defaultConfigPath in fetchit pod 221 | // regardless of where the config file is on the host, fetchit will read the configFile from within 222 | // the pod at /opt/mount 223 | if initial { 224 | if _, err := os.Stat(filepath.Dir(defaultConfigPath)); err != nil { 225 | if envURL == "" { 226 | cobra.CheckErr(fmt.Errorf("the local config file must be mounted to /opt/mount directory at /opt/mount/config.yaml in the fetchit pod: %v", err)) 227 | } 228 | } 229 | } 230 | 231 | config, isLocal, err = isLocalConfig(v) 232 | if (initial && !isLocal) || err != nil { 233 | // Only run this from initial startup and only after trying to populate the config from a local file. 234 | // because CheckForConfigUpdates also runs with each processConfig, so if !initial this is already done 235 | // If configURL is passed in, a config file on disk has priority on the initial run. 236 | _ = checkForConfigUpdates(envURL, false, true, "", "", "") 237 | } 238 | 239 | // if config is not yet populated, fc.CheckForConfigUpdates has placed the config 240 | // downloaded from URL to the defaultconfigPath 241 | if !isLocal { 242 | // If not initial run, only way to get here is if already determined need for reload 243 | // with an updated config placed in defaultConfigPath. 244 | config, exists, err = readConfig(v) 245 | if config == nil || !exists || err != nil { 246 | if err != nil { 247 | cobra.CheckErr(fmt.Errorf("Could not populate config, tried %s in fetchit pod and also URL: %s. Ensure local config is mounted or served from a URL and try again.", defaultConfigPath, envURL)) 248 | } 249 | cobra.CheckErr(fmt.Errorf("Error locating config, tried %s in fetchit pod and also URL %s. Ensure local config is mounted or served from a URL and try again: %v", defaultConfigPath, envURL, err)) 250 | } 251 | } 252 | 253 | if config == nil { 254 | cobra.CheckErr("no fetchit targets found, exiting") 255 | } 256 | 257 | return fc.populateFetchit(config) 258 | } 259 | 260 | // Takes target from user and converts it for internal use 261 | func getMethodTargetScheds(targetConfigs []*TargetConfig, fetchit *Fetchit) *Fetchit { 262 | for _, tc := range targetConfigs { 263 | tc.mu.Lock() 264 | defer tc.mu.Unlock() 265 | internalTarget := &Target{ 266 | url: tc.Url, 267 | device: tc.Device, 268 | pat: fetchit.pat, 269 | // define the environment variable for envSecret 270 | envSecret: fetchit.envSecret, 271 | ssh: fetchit.ssh, 272 | sshKey: fetchit.sshKey, 273 | username: fetchit.username, 274 | password: fetchit.password, 275 | branch: tc.Branch, 276 | disconnected: tc.Disconnected, 277 | } 278 | 279 | if tc.VerifyCommitsInfo != nil { 280 | internalTarget.gitsignVerify = tc.VerifyCommitsInfo.GitsignVerify 281 | internalTarget.gitsignRekorURL = tc.VerifyCommitsInfo.GitsignRekorURL 282 | } 283 | 284 | if tc.configReload != nil { 285 | tc.configReload.target = internalTarget 286 | tc.configReload.initialRun = true 287 | fetchit.methodTargetScheds[tc.configReload] = tc.configReload.SchedInfo() 288 | fetchit.allMethodTypes[configFileMethod] = struct{}{} 289 | } 290 | 291 | if tc.prune != nil { 292 | tc.prune.target = internalTarget 293 | fetchit.methodTargetScheds[tc.prune] = tc.prune.SchedInfo() 294 | fetchit.allMethodTypes[pruneMethod] = struct{}{} 295 | 296 | } 297 | 298 | if tc.image != nil { 299 | tc.image.target = internalTarget 300 | tc.image.initialRun = true 301 | fetchit.methodTargetScheds[tc.image] = tc.image.SchedInfo() 302 | fetchit.allMethodTypes[imageMethod] = struct{}{} 303 | 304 | } 305 | 306 | if len(tc.Ansible) > 0 { 307 | fetchit.allMethodTypes[ansibleMethod] = struct{}{} 308 | for _, a := range tc.Ansible { 309 | a.initialRun = true 310 | a.target = internalTarget 311 | fetchit.methodTargetScheds[a] = a.SchedInfo() 312 | } 313 | } 314 | if len(tc.FileTransfer) > 0 { 315 | fetchit.allMethodTypes[filetransferMethod] = struct{}{} 316 | for _, ft := range tc.FileTransfer { 317 | ft.initialRun = true 318 | ft.target = internalTarget 319 | fetchit.methodTargetScheds[ft] = ft.SchedInfo() 320 | } 321 | } 322 | if len(tc.Kube) > 0 { 323 | fetchit.allMethodTypes[kubeMethod] = struct{}{} 324 | for _, k := range tc.Kube { 325 | k.initialRun = true 326 | k.target = internalTarget 327 | fetchit.methodTargetScheds[k] = k.SchedInfo() 328 | } 329 | } 330 | if len(tc.Raw) > 0 { 331 | fetchit.allMethodTypes[rawMethod] = struct{}{} 332 | for _, r := range tc.Raw { 333 | r.initialRun = true 334 | r.target = internalTarget 335 | fetchit.methodTargetScheds[r] = r.SchedInfo() 336 | } 337 | } 338 | if len(tc.Systemd) > 0 { 339 | fetchit.allMethodTypes[systemdMethod] = struct{}{} 340 | for _, sd := range tc.Systemd { 341 | sd.initialRun = true 342 | sd.target = internalTarget 343 | fetchit.methodTargetScheds[sd] = sd.SchedInfo() 344 | } 345 | } 346 | } 347 | return fetchit 348 | } 349 | 350 | func (f *Fetchit) RunTargets() { 351 | for method := range f.methodTargetScheds { 352 | // ConfigReload, PodmanAutoUpdateAll, Image, Prune methods do not include git URL 353 | if method.GetTarget().url != "" { 354 | if err := getRepo(method.GetTarget()); err != nil { 355 | logger.Debugf("Target: %s, clone error: %v, will retry next scheduled run", method.GetTarget(), err) 356 | } 357 | } 358 | } 359 | 360 | s := f.scheduler 361 | for method, schedInfo := range f.methodTargetScheds { 362 | skew := 0 363 | if schedInfo.skew != nil { 364 | skew = rand.Intn(*schedInfo.skew) 365 | } 366 | ctx, cancel := context.WithCancel(context.Background()) 367 | defer cancel() 368 | mt := method.GetKind() 369 | logger.Infof("Processing git target: %s Method: %s Name: %s", method.GetTarget().url, mt, method.GetName()) 370 | s.Cron(schedInfo.schedule).Tag(mt).Do(method.Process, ctx, f.conn, skew) 371 | s.StartImmediately() 372 | } 373 | s.StartAsync() 374 | select {} 375 | } 376 | 377 | func getRepo(target *Target) error { 378 | if target.url != "" && !target.disconnected { 379 | getClone(target) 380 | } else if target.disconnected && len(target.url) > 0 { 381 | getDisconnected(target) 382 | } else if target.disconnected && len(target.device) > 0 { 383 | getDeviceDisconnected(target) 384 | } 385 | return nil 386 | } 387 | 388 | func getClone(target *Target) error { 389 | directory := getDirectory(target) 390 | absPath, err := filepath.Abs(directory) 391 | if err != nil { 392 | return err 393 | } 394 | var exists bool 395 | if _, err := os.Stat(directory); err == nil { 396 | exists = true 397 | // if directory/.git does not exist, fail quickly 398 | if _, err := os.Stat(directory + "/.git"); err != nil { 399 | return fmt.Errorf("%s exists but is not a git repository", directory) 400 | } 401 | } else if !os.IsNotExist(err) { 402 | return err 403 | } 404 | if !exists { 405 | logger.Infof("git clone %s %s --recursive", target.url, target.branch) 406 | // if the envSecret is set, use it as variable target.PAT 407 | if target.envSecret != "" { 408 | target.pat = os.Getenv(target.envSecret) 409 | logger.Infof("Using the envSecret %s", target.envSecret) 410 | } 411 | if target.pat != "" { 412 | target.username = "fetchit" 413 | target.password = target.pat 414 | } 415 | // default to using existing http method 416 | cOptions := &git.CloneOptions{ 417 | Auth: &githttp.BasicAuth{ 418 | Username: target.username, // the value of this field should not matter when using a PAT 419 | Password: target.password, 420 | }, 421 | URL: target.url, 422 | ReferenceName: plumbing.ReferenceName(fmt.Sprintf("refs/heads/%s", target.branch)), 423 | SingleBranch: true, 424 | } 425 | // if using ssh, change auth to use ssh key 426 | if target.ssh { 427 | logger.Infof("git clone %s using SSH key %s ", target.url, target.sshKey) 428 | authValue, err := ssh.NewPublicKeysFromFile("git", target.sshKey, target.password) 429 | if err != nil { 430 | logger.Infof("generate publickeys failed: %s", err.Error()) 431 | return err 432 | } 433 | cOptions.Auth = authValue 434 | } 435 | _, err := git.PlainClone(absPath, false, cOptions) 436 | if err != nil { 437 | logger.Infof("git clone failed: %s", err.Error()) 438 | return err 439 | } 440 | } 441 | return nil 442 | } 443 | 444 | func getDisconnected(target *Target) error { 445 | directory := getDirectory(target) 446 | var exists bool 447 | if _, err := os.Stat(directory); err == nil { 448 | exists = true 449 | // if directory/.git does not exist, fail quickly 450 | if _, err := os.Stat(directory + "/.git"); err != nil { 451 | return fmt.Errorf("%s exists but is not a git repository", directory) 452 | } 453 | } else if !os.IsNotExist(err) { 454 | return err 455 | } 456 | if !exists { 457 | extractZip(target.url) 458 | } 459 | return nil 460 | } 461 | 462 | func getDeviceDisconnected(target *Target) error { 463 | directory := getDirectory(target) 464 | var exists bool 465 | if _, err := os.Stat(directory); err == nil { 466 | exists = true 467 | // if directory/.git does not exist, fail quickly 468 | if _, err := os.Stat(directory + "/.git"); err != nil { 469 | return fmt.Errorf("%s exists but is not a git repository", directory) 470 | } 471 | } else if !os.IsNotExist(err) { 472 | return err 473 | } 474 | if !exists { 475 | localDevicePull(directory, target.device, "", false) 476 | } 477 | return nil 478 | } 479 | -------------------------------------------------------------------------------- /pkg/engine/filetransfer.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "context" 5 | "path/filepath" 6 | "time" 7 | 8 | "github.com/go-git/go-git/v5/plumbing" 9 | "github.com/go-git/go-git/v5/plumbing/object" 10 | ) 11 | 12 | const filetransferMethod = "filetransfer" 13 | 14 | // FileTransfer to place files on host system 15 | type FileTransfer struct { 16 | CommonMethod `mapstructure:",squash"` 17 | // Directory path on the host system in which the target files should be placed 18 | DestinationDirectory string `mapstructure:"destinationDirectory"` 19 | } 20 | 21 | func (ft *FileTransfer) GetKind() string { 22 | return filetransferMethod 23 | } 24 | 25 | func (ft *FileTransfer) Process(ctx, conn context.Context, skew int) { 26 | target := ft.GetTarget() 27 | time.Sleep(time.Duration(skew) * time.Millisecond) 28 | target.mu.Lock() 29 | defer target.mu.Unlock() 30 | 31 | if ft.initialRun { 32 | err := getRepo(target) 33 | if err != nil { 34 | if len(target.url) > 0 { 35 | logger.Errorf("Failed to clone repository at %s: %v", target.url, err) 36 | return 37 | } else if len(target.localPath) > 0 { 38 | logger.Errorf("Failed to clone repository %s: %v", target.localPath, err) 39 | return 40 | } 41 | } 42 | 43 | err = zeroToCurrent(ctx, conn, ft, target, nil) 44 | if err != nil { 45 | logger.Errorf("Error moving to current: %v target url is: %s ", err, target.url) 46 | return 47 | } 48 | } 49 | 50 | err := currentToLatest(ctx, conn, ft, target, nil) 51 | if err != nil { 52 | logger.Errorf("Error moving current to latest: %v", err) 53 | return 54 | } 55 | 56 | ft.initialRun = false 57 | } 58 | 59 | func (ft *FileTransfer) MethodEngine(ctx, conn context.Context, change *object.Change, path string) error { 60 | var prev *string = nil 61 | if change != nil { 62 | if change.To.Name != "" { 63 | prev = &change.To.Name 64 | } 65 | } 66 | dest := ft.DestinationDirectory 67 | return ft.fileTransferPodman(ctx, conn, path, dest, prev) 68 | } 69 | 70 | func (ft *FileTransfer) Apply(ctx, conn context.Context, currentState, desiredState plumbing.Hash, tags *[]string) error { 71 | changeMap, err := applyChanges(ctx, ft.GetTarget(), ft.GetTargetPath(), ft.Glob, currentState, desiredState, tags) 72 | if err != nil { 73 | return err 74 | } 75 | if err := runChanges(ctx, conn, ft, changeMap); err != nil { 76 | return err 77 | } 78 | return nil 79 | } 80 | 81 | func (ft *FileTransfer) fileTransferPodman(ctx, conn context.Context, path, dest string, prev *string) error { 82 | if prev != nil { 83 | pathToRemove := filepath.Join(dest, filepath.Base(*prev)) 84 | s := generateSpecRemove(filetransferMethod, filepath.Base(pathToRemove), pathToRemove, dest, ft.Name) 85 | createResponse, err := createAndStartContainer(conn, s) 86 | if err != nil { 87 | return err 88 | } 89 | 90 | err = waitAndRemoveContainer(conn, createResponse.ID) 91 | if err != nil { 92 | return err 93 | } 94 | } 95 | 96 | if path == deleteFile { 97 | return nil 98 | } 99 | 100 | logger.Infof("Deploying file(s) %s", path) 101 | 102 | file := filepath.Base(path) 103 | 104 | source := filepath.Join("/opt", path) 105 | copyFile := (source + " " + dest) 106 | 107 | s := generateSpec(filetransferMethod, file, copyFile, dest, ft.Name) 108 | createResponse, err := createAndStartContainer(conn, s) 109 | if err != nil { 110 | return err 111 | } 112 | 113 | // Wait for the container to exit 114 | return waitAndRemoveContainer(conn, createResponse.ID) 115 | } 116 | -------------------------------------------------------------------------------- /pkg/engine/gitauth.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "os" 5 | "path/filepath" 6 | ) 7 | 8 | var defaultSSHKey = filepath.Join("/opt", "mount", ".ssh", "id_rsa") 9 | 10 | // Basic type needed for ssh authentication 11 | type GitAuth struct { 12 | SSH bool `mapstructure:"ssh"` 13 | SSHKeyFile string `mapstructure:"sshKeyFile"` 14 | Username string `mapstructure:"username"` 15 | Password string `mapstructure:"password"` 16 | PAT string `mapstructure:"pat"` 17 | EnvSecret string `mapstructure:"envSecret"` 18 | } 19 | 20 | // Checks to see if private key exists on given path 21 | func checkForPrivateKey(path string) error { 22 | if _, err := os.Stat(path); err != nil { 23 | return err 24 | } 25 | return nil 26 | } 27 | -------------------------------------------------------------------------------- /pkg/engine/image.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "context" 5 | "io" 6 | "net/http" 7 | "os" 8 | "path" 9 | "path/filepath" 10 | "time" 11 | 12 | "github.com/containers/podman/v4/libpod/define" 13 | "github.com/containers/podman/v4/pkg/bindings/containers" 14 | "github.com/containers/podman/v4/pkg/bindings/images" 15 | "github.com/go-git/go-git/v5/plumbing" 16 | "github.com/go-git/go-git/v5/plumbing/object" 17 | ) 18 | 19 | const imageMethod = "image" 20 | 21 | // Image configures targets to run a system prune periodically 22 | type Image struct { 23 | CommonMethod `mapstructure:",squash"` 24 | // Url is the url of the image to be loaded onto the system 25 | Url string `mapstructure:"url"` 26 | // ImagePath defines the location of the image to import 27 | ImagePath string `mapstructure:"imagePath"` 28 | // Device is the device that the image is stored(USB) 29 | Device string `mapstructure:"device"` 30 | } 31 | 32 | func (i *Image) GetKind() string { 33 | return imageMethod 34 | } 35 | 36 | func (i *Image) Process(ctx, conn context.Context, skew int) { 37 | target := i.GetTarget() 38 | time.Sleep(time.Duration(skew) * time.Millisecond) 39 | target.mu.Lock() 40 | defer target.mu.Unlock() 41 | 42 | if len(i.Url) > 0 { 43 | err := i.loadHTTPPodman(ctx, conn, i.Url) 44 | if err != nil { 45 | logger.Debugf("Repository: %s Method: %s encountered error: %v, resetting...", target.url, imageMethod, err) 46 | } 47 | } else if len(i.ImagePath) > 0 { 48 | err := i.loadDevicePodman(ctx, conn) 49 | if err != nil { 50 | logger.Debugf("Repository: %s Method: %s encountered error: %v, resetting...", target.url, imageMethod, err) 51 | } 52 | } 53 | } 54 | 55 | func (i *Image) MethodEngine(ctx context.Context, conn context.Context, change *object.Change, path string) error { 56 | return nil 57 | } 58 | 59 | func (i *Image) Apply(ctx, conn context.Context, currentState, desiredState plumbing.Hash, tags *[]string) error { 60 | return nil 61 | } 62 | 63 | func (i *Image) loadHTTPPodman(ctx, conn context.Context, url string) error { 64 | imageName := (path.Base(url)) 65 | pathToLoad := "/opt/" + imageName 66 | data, err := http.Get(url) 67 | if err != nil { 68 | // logger.Info("Failed to get image from url ", url) saving this for if we do various log levels 69 | // remove the image if it exists 70 | if _, err := os.Stat(pathToLoad); err != nil { 71 | logger.Info("URL not present...requeuing") 72 | return nil 73 | } 74 | logger.Info("Flushing image from device ", pathToLoad) 75 | flushImages(pathToLoad) 76 | return nil 77 | } 78 | if data.StatusCode == http.StatusOK { 79 | if _, err := os.Stat(pathToLoad); os.IsNotExist(err) { 80 | logger.Infof("Loading image from %s", url) 81 | // Place the data into the placeholder file 82 | defer data.Body.Close() 83 | 84 | // Fail early if http error code is not 200 85 | if data.StatusCode != http.StatusOK { 86 | logger.Error("Failed getting data from ", i.Url) 87 | return err 88 | } 89 | // Create the file to write the data to 90 | file, err := os.Create("/opt/" + imageName) 91 | if err != nil { 92 | logger.Error("Failed creating file ", file) 93 | return err 94 | } 95 | // Write the data to the file 96 | _, err = io.Copy(file, data.Body) 97 | if err != nil { 98 | logger.Error("Failed writing data to ", file) 99 | return err 100 | } 101 | 102 | err = i.podmanImageLoad(ctx, conn, pathToLoad) 103 | if err != nil { 104 | logger.Error("Failed to load image from device") 105 | return err 106 | } 107 | return nil 108 | } else { 109 | return nil 110 | } 111 | } 112 | return nil 113 | } 114 | 115 | func (i *Image) loadDevicePodman(ctx, conn context.Context) error { 116 | // Define the path to the image 117 | trimDir := filepath.Base(i.ImagePath) 118 | baseDir := filepath.Dir(i.ImagePath) 119 | pathToLoad := "/opt/" + i.ImagePath 120 | _, exitCode, err := localDeviceCheck(baseDir, i.Device, trimDir) 121 | if err != nil { 122 | logger.Error("Failed to check device") 123 | return err 124 | } 125 | if exitCode != 0 { 126 | logger.Info("Device not present...requeuing") 127 | // List files to see if anything needs to be flushed 128 | if _, err := os.Stat(pathToLoad); err == nil { 129 | logger.Info("Flushing image from device ", pathToLoad) 130 | flushImages(pathToLoad) 131 | } 132 | return nil 133 | } else if exitCode == 0 { 134 | // If file does not exist pull from the device 135 | if _, err := os.Stat(pathToLoad); os.IsNotExist(err) { 136 | id, err := localDevicePull(baseDir, i.Device, "-"+trimDir, true) 137 | if err != nil { 138 | logger.Info("Issue pulling image from device ", err) 139 | } 140 | 141 | // Wait for the image to be copied into the fetchit container 142 | containers.Wait(conn, id, new(containers.WaitOptions).WithCondition([]define.ContainerStatus{stopped})) 143 | } 144 | err = i.podmanImageLoad(ctx, conn, pathToLoad) 145 | if err != nil { 146 | logger.Error("Failed to load image ", pathToLoad) 147 | return err 148 | } 149 | return nil 150 | } 151 | return nil 152 | } 153 | 154 | func (i *Image) podmanImageLoad(ctx, conn context.Context, pathToLoad string) error { 155 | // Load image from path on the system using podman load 156 | // Read the file that needs to be processed 157 | logger.Infof("Loading image from %s", i.ImagePath) 158 | 159 | file, err := os.Open(pathToLoad) 160 | if err != nil { 161 | logger.Error("Failed opening file ", pathToLoad) 162 | return err 163 | } 164 | defer file.Close() 165 | imported, err := images.Load(conn, file) 166 | if err != nil { 167 | os.Remove(pathToLoad) 168 | return err 169 | } 170 | 171 | logger.Infof("Image %s loaded....Requeuing", imported.Names[0]) 172 | return nil 173 | } 174 | 175 | func flushImages(imagePath string) { 176 | if _, err := os.Stat(imagePath); err == nil { 177 | os.Remove(imagePath) 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /pkg/engine/kube.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "encoding/json" 7 | "errors" 8 | "io" 9 | "io/ioutil" 10 | "net/http" 11 | "strings" 12 | "time" 13 | 14 | "github.com/containers/fetchit/pkg/engine/utils" 15 | "github.com/containers/podman/v4/pkg/bindings" 16 | "github.com/containers/podman/v4/pkg/bindings/play" 17 | "github.com/containers/podman/v4/pkg/domain/entities" 18 | "github.com/go-git/go-git/v5/plumbing" 19 | "github.com/go-git/go-git/v5/plumbing/object" 20 | 21 | "gopkg.in/yaml.v3" 22 | v1 "k8s.io/api/core/v1" 23 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 24 | k8syaml "sigs.k8s.io/yaml" 25 | ) 26 | 27 | const kubeMethod = "kube" 28 | 29 | // Kube to launch pods using podman kube-play 30 | type Kube struct { 31 | CommonMethod `mapstructure:",squash"` 32 | } 33 | 34 | func (k *Kube) GetKind() string { 35 | return kubeMethod 36 | } 37 | 38 | func (k *Kube) Process(ctx, conn context.Context, skew int) { 39 | target := k.GetTarget() 40 | time.Sleep(time.Duration(skew) * time.Millisecond) 41 | target.mu.Lock() 42 | defer target.mu.Unlock() 43 | 44 | initial := k.initialRun 45 | tag := []string{"yaml", "yml"} 46 | if initial { 47 | err := getRepo(target) 48 | if err != nil { 49 | logger.Errorf("Failed to clone repository %s: %v", target.url, err) 50 | return 51 | } 52 | 53 | err = zeroToCurrent(ctx, conn, k, target, &tag) 54 | if err != nil { 55 | logger.Errorf("Error moving to current: %v", err) 56 | return 57 | } 58 | } 59 | 60 | err := currentToLatest(ctx, conn, k, target, &tag) 61 | if err != nil { 62 | logger.Errorf("Error moving current to latest: %v", err) 63 | return 64 | } 65 | 66 | k.initialRun = false 67 | } 68 | 69 | func (k *Kube) MethodEngine(ctx context.Context, conn context.Context, change *object.Change, path string) error { 70 | prev, err := getChangeString(change) 71 | if err != nil { 72 | return err 73 | } 74 | return k.kubePodman(ctx, conn, path, prev) 75 | } 76 | 77 | func (k *Kube) Apply(ctx, conn context.Context, currentState, desiredState plumbing.Hash, tags *[]string) error { 78 | changeMap, err := applyChanges(ctx, k.GetTarget(), k.GetTargetPath(), k.Glob, currentState, desiredState, tags) 79 | if err != nil { 80 | return err 81 | } 82 | if err := runChanges(ctx, conn, k, changeMap); err != nil { 83 | return err 84 | } 85 | return nil 86 | } 87 | 88 | func (k *Kube) kubePodman(ctx, conn context.Context, path string, prev *string) error { 89 | if path != deleteFile { 90 | logger.Infof("Creating podman container from %s using kube method", path) 91 | } 92 | 93 | if prev != nil { 94 | err := stopPods(conn, []byte(*prev)) 95 | if err != nil { 96 | return utils.WrapErr(err, "Error stopping pods") 97 | } 98 | } 99 | 100 | if path != deleteFile { 101 | kubeYaml, err := ioutil.ReadFile(path) 102 | if err != nil { 103 | return utils.WrapErr(err, "Error reading file") 104 | } 105 | 106 | // Try stopping the pods, don't care if they don't exist 107 | err = stopPods(conn, kubeYaml) 108 | if err != nil { 109 | if !strings.Contains(err.Error(), "no such pod") { 110 | return utils.WrapErr(err, "Error stopping pods") 111 | } 112 | } 113 | 114 | err = createPods(conn, path, kubeYaml) 115 | if err != nil { 116 | return utils.WrapErr(err, "Error creating pod") 117 | } 118 | } 119 | 120 | return nil 121 | } 122 | 123 | func stopPods(ctx context.Context, podSpec []byte) error { 124 | conn, err := bindings.GetClient(ctx) 125 | if err != nil { 126 | return utils.WrapErr(err, "Error getting podman connection") 127 | } 128 | 129 | response, err := conn.DoRequest(ctx, bytes.NewReader(podSpec), http.MethodDelete, "/play/kube", nil, nil) 130 | if err != nil { 131 | return utils.WrapErr(err, "Error making podman API call to delete pod") 132 | } 133 | 134 | var report entities.PlayKubeReport 135 | if err := response.Process(&report); err != nil { 136 | return utils.WrapErr(err, "Error processing podman response when deleting pod") 137 | } 138 | 139 | return nil 140 | } 141 | 142 | func createPods(ctx context.Context, path string, specs []byte) error { 143 | pod_list, err := podFromBytes(specs) 144 | if err != nil { 145 | return utils.WrapErr(err, "Error getting list of pods in spec") 146 | } 147 | 148 | for _, pod := range pod_list { 149 | err = validatePod(pod) 150 | if err != nil { 151 | return utils.WrapErr(err, "Error validating pod spec") 152 | } 153 | } 154 | 155 | _, err = play.Kube(ctx, path, nil) 156 | if err != nil { 157 | return utils.WrapErr(err, "Error playing kube spec") 158 | } 159 | 160 | logger.Infof("Created pods from spec in %s", path) 161 | return nil 162 | } 163 | 164 | func podFromBytes(input []byte) ([]v1.Pod, error) { 165 | var t metav1.TypeMeta 166 | d := yaml.NewDecoder(bytes.NewReader(input)) 167 | ret := make([]v1.Pod, 0) 168 | 169 | for { 170 | var i interface{} 171 | err := d.Decode(&i) 172 | if err == io.EOF { 173 | break 174 | } 175 | if err != nil { 176 | return ret, utils.WrapErr(err, "Error decoding yaml") 177 | } 178 | 179 | o, err := yaml.Marshal(i) 180 | if err != nil { 181 | return ret, utils.WrapErr(err, "Error marshalling yaml into object for conversion to json") 182 | } 183 | 184 | b, err := k8syaml.YAMLToJSON(o) 185 | if err != nil { 186 | return ret, utils.WrapErr(err, "Error converting yaml to json") 187 | } 188 | 189 | err = json.Unmarshal(b, &t) 190 | if err != nil { 191 | return ret, utils.WrapErr(err, "Error unmarshalling json object") 192 | } 193 | 194 | if t.Kind != "Pod" { 195 | continue 196 | } 197 | 198 | pod := v1.Pod{} 199 | err = json.Unmarshal(b, &pod) 200 | if err != nil { 201 | return ret, utils.WrapErr(err, "Error unmarshalling json into pod object") 202 | } 203 | 204 | ret = append(ret, pod) 205 | } 206 | 207 | return ret, nil 208 | } 209 | 210 | func validatePod(p v1.Pod) error { 211 | for _, container := range p.Spec.Containers { 212 | if container.Name == p.ObjectMeta.Name { 213 | return errors.New("pod and container within pod cannot share same name for Podman v3") 214 | } 215 | } 216 | return nil 217 | } 218 | -------------------------------------------------------------------------------- /pkg/engine/raw.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "encoding/json" 7 | "io/ioutil" 8 | "time" 9 | 10 | "github.com/containers/common/libnetwork/types" 11 | "github.com/containers/fetchit/pkg/engine/utils" 12 | "github.com/containers/podman/v4/pkg/bindings/containers" 13 | "github.com/containers/podman/v4/pkg/specgen" 14 | "github.com/go-git/go-git/v5/plumbing" 15 | "github.com/go-git/go-git/v5/plumbing/object" 16 | "github.com/opencontainers/runtime-spec/specs-go" 17 | "gopkg.in/yaml.v3" 18 | ) 19 | 20 | const ( 21 | rawMethod = "raw" 22 | FetchItLabel = "fetchit" 23 | ) 24 | 25 | // Raw to deploy pods from json or yaml files 26 | type Raw struct { 27 | CommonMethod `mapstructure:",squash"` 28 | // Pull images configured in target files each time regardless of if it already exists 29 | PullImage bool `mapstructure:"pullImage"` 30 | } 31 | 32 | func (r *Raw) GetKind() string { 33 | return rawMethod 34 | } 35 | 36 | /* below is an example.json file: 37 | {"Image":"docker.io/mmumshad/simple-webapp-color:latest", 38 | "Name": "colors", 39 | "Env": {"color": "blue", "tree": "trunk"}, 40 | "Ports": [{ 41 | "HostIP": "", 42 | "ContainerPort": 8080, 43 | "HostPort": 8080, 44 | "Range": 0, 45 | "Protocol": ""}] 46 | "CapAdd": [] 47 | "CapDrop": [] 48 | } 49 | */ 50 | 51 | type port struct { 52 | HostIP string `json:"host_ip" yaml:"host_ip"` 53 | ContainerPort uint16 `json:"container_port" yaml:"container_port"` 54 | HostPort uint16 `json:"host_port" yaml:"host_port"` 55 | Range uint16 `json:"range" yaml:"range"` 56 | Protocol string `json:"protocol" yaml:"protocol"` 57 | } 58 | 59 | type mount struct { 60 | Destination string `json:"destination" yaml:"destination"` 61 | Type string `json:"type,omitempty" yaml:"type,omitempty" platform:"linux,solaris,zos"` 62 | Source string `json:"source,omitempty" yaml:"source,omitempty"` 63 | Options []string `json:"options,omitempty" yaml:"options,omitempty"` 64 | } 65 | 66 | type namedVolume struct { 67 | Name string `json:"name" yaml:"name"` 68 | Dest string `json:"dest" yaml:"dest"` 69 | Options []string `json:"options" yaml:"options"` 70 | } 71 | 72 | type RawPod struct { 73 | Image string `json:"Image" yaml:"Image"` 74 | Name string `json:"Name" yaml:"Name"` 75 | Env map[string]string `json:"Env" yaml:"Env"` 76 | Ports []port `json:"Ports" yaml:"Ports"` 77 | Mounts []mount `json:"Mounts" yaml:"Mounts"` 78 | Volumes []namedVolume `json:"Volumes" yaml:"Volumes"` 79 | CapAdd []string `json:"CapAdd" yaml:"CapAdd"` 80 | CapDrop []string `json:"CapDrop" yaml:"CapDrop"` 81 | } 82 | 83 | func (r *Raw) Process(ctx context.Context, conn context.Context, skew int) { 84 | time.Sleep(time.Duration(skew) * time.Millisecond) 85 | target := r.GetTarget() 86 | target.mu.Lock() 87 | defer target.mu.Unlock() 88 | 89 | tag := []string{".json", ".yaml", ".yml"} 90 | 91 | if r.initialRun { 92 | err := getRepo(target) 93 | if err != nil { 94 | logger.Errorf("Failed to clone repository %s: %v", target.url, err) 95 | return 96 | } 97 | 98 | err = zeroToCurrent(ctx, conn, r, target, &tag) 99 | if err != nil { 100 | logger.Errorf("Error moving to current: %v", err) 101 | return 102 | } 103 | } 104 | 105 | err := currentToLatest(ctx, conn, r, target, &tag) 106 | if err != nil { 107 | logger.Errorf("Error moving current to latest: %v", err) 108 | return 109 | } 110 | 111 | r.initialRun = false 112 | } 113 | 114 | func (r *Raw) rawPodman(ctx, conn context.Context, path string, prev *string) error { 115 | 116 | logger.Infof("Creating podman container from %s", path) 117 | 118 | rawFile, err := ioutil.ReadFile(path) 119 | if err != nil { 120 | return err 121 | } 122 | 123 | raw, err := rawPodFromBytes(rawFile) 124 | if err != nil { 125 | return err 126 | } 127 | 128 | logger.Infof("Identifying if image exists locally") 129 | 130 | err = detectOrFetchImage(conn, raw.Image, r.PullImage) 131 | if err != nil { 132 | return err 133 | } 134 | 135 | // Delete previous file's podxz 136 | if prev != nil { 137 | raw, err := rawPodFromBytes([]byte(*prev)) 138 | if err != nil { 139 | return err 140 | } 141 | 142 | err = deleteContainer(conn, raw.Name) 143 | if err != nil { 144 | return err 145 | } 146 | 147 | logger.Infof("Deleted podman container %s", raw.Name) 148 | } 149 | 150 | if path == deleteFile { 151 | return nil 152 | } 153 | 154 | err = removeExisting(conn, raw.Name) 155 | if err != nil { 156 | return err 157 | } 158 | 159 | s := createSpecGen(*raw) 160 | 161 | createResponse, err := containers.CreateWithSpec(conn, s, nil) 162 | if err != nil { 163 | return err 164 | } 165 | logger.Infof("Container %s created.", s.Name) 166 | 167 | if err := containers.Start(conn, createResponse.ID, nil); err != nil { 168 | return err 169 | } 170 | logger.Infof("Container %s started....Requeuing", s.Name) 171 | 172 | return nil 173 | } 174 | 175 | func (r *Raw) MethodEngine(ctx context.Context, conn context.Context, change *object.Change, path string) error { 176 | prev, err := getChangeString(change) 177 | if err != nil { 178 | return err 179 | } 180 | return r.rawPodman(ctx, conn, path, prev) 181 | } 182 | 183 | func (r *Raw) Apply(ctx, conn context.Context, currentState, desiredState plumbing.Hash, tags *[]string) error { 184 | changeMap, err := applyChanges(ctx, r.GetTarget(), r.GetTargetPath(), r.Glob, currentState, desiredState, tags) 185 | if err != nil { 186 | return err 187 | } 188 | if err := runChanges(ctx, conn, r, changeMap); err != nil { 189 | return err 190 | } 191 | return nil 192 | } 193 | 194 | func convertMounts(mounts []mount) []specs.Mount { 195 | result := []specs.Mount{} 196 | for _, m := range mounts { 197 | toAppend := specs.Mount{ 198 | Destination: m.Destination, 199 | Type: m.Type, 200 | Source: m.Source, 201 | Options: m.Options, 202 | } 203 | result = append(result, toAppend) 204 | } 205 | return result 206 | } 207 | 208 | func convertPorts(ports []port) []types.PortMapping { 209 | result := []types.PortMapping{} 210 | for _, p := range ports { 211 | toAppend := types.PortMapping{ 212 | HostIP: p.HostIP, 213 | ContainerPort: p.ContainerPort, 214 | HostPort: p.HostPort, 215 | Range: p.Range, 216 | Protocol: p.Protocol, 217 | } 218 | result = append(result, toAppend) 219 | } 220 | return result 221 | } 222 | 223 | func convertVolumes(namedVolumes []namedVolume) []*specgen.NamedVolume { 224 | result := []*specgen.NamedVolume{} 225 | for _, n := range namedVolumes { 226 | toAppend := specgen.NamedVolume{ 227 | Name: n.Name, 228 | Dest: n.Dest, 229 | Options: n.Options, 230 | } 231 | result = append(result, &toAppend) 232 | } 233 | return result 234 | } 235 | 236 | func createSpecGen(raw RawPod) *specgen.SpecGenerator { 237 | // Create a new container 238 | s := specgen.NewSpecGenerator(raw.Image, false) 239 | s.Name = raw.Name 240 | s.Env = map[string]string(raw.Env) 241 | s.Mounts = convertMounts(raw.Mounts) 242 | s.PortMappings = convertPorts(raw.Ports) 243 | s.Volumes = convertVolumes(raw.Volumes) 244 | s.CapAdd = []string(raw.CapAdd) 245 | s.CapDrop = []string(raw.CapDrop) 246 | s.RestartPolicy = "always" 247 | // add a label to signify ownership of fetchit <--> this container 248 | s.Labels = map[string]string{ 249 | "owned-by": FetchItLabel, 250 | } 251 | return s 252 | } 253 | 254 | func deleteContainer(conn context.Context, podName string) error { 255 | err := containers.Stop(conn, podName, nil) 256 | if err != nil { 257 | return err 258 | } 259 | 260 | containers.Remove(conn, podName, new(containers.RemoveOptions).WithForce(true)) 261 | if err != nil { 262 | return err 263 | } 264 | 265 | return nil 266 | } 267 | 268 | func rawPodFromBytes(b []byte) (*RawPod, error) { 269 | b = bytes.TrimSpace(b) 270 | raw := RawPod{} 271 | if b[0] == '{' { 272 | err := json.Unmarshal(b, &raw) 273 | if err != nil { 274 | return nil, utils.WrapErr(err, "Unable to unmarshal json") 275 | } 276 | } else { 277 | err := yaml.Unmarshal(b, &raw) 278 | if err != nil { 279 | return nil, utils.WrapErr(err, "Unable to unmarshal yaml") 280 | } 281 | } 282 | return &raw, nil 283 | } 284 | 285 | // Using this might not be necessary 286 | func removeExisting(conn context.Context, podName string) error { 287 | inspectData, err := containers.Inspect(conn, podName, new(containers.InspectOptions).WithSize(true)) 288 | if err == nil || inspectData == nil { 289 | logger.Infof("A container named %s already exists. Removing the container before redeploy.", podName) 290 | err := deleteContainer(conn, podName) 291 | if err != nil { 292 | return err 293 | } 294 | } 295 | 296 | return nil 297 | } 298 | -------------------------------------------------------------------------------- /pkg/engine/start.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "github.com/natefinch/lumberjack" 5 | "github.com/spf13/cobra" 6 | "go.uber.org/zap" 7 | "go.uber.org/zap/zapcore" 8 | "os" 9 | ) 10 | 11 | // This file will be created within the fetchit pod 12 | const logFile = "/opt/mount/fetchit.log" 13 | 14 | var startCmd = &cobra.Command{ 15 | Use: "start", 16 | Short: "Start fetchit engine", 17 | Long: `Start fetchit engine`, 18 | Run: func(cmd *cobra.Command, args []string) { 19 | fetchit = fetchitConfig.InitConfig(true) 20 | fetchit.RunTargets() 21 | }, 22 | } 23 | 24 | var logger *zap.SugaredLogger 25 | 26 | func init() { 27 | fetchitConfig = newFetchitConfig() 28 | fetchitCmd.AddCommand(startCmd) 29 | } 30 | 31 | func InitLogger() { 32 | syncer := zap.CombineWriteSyncers(os.Stdout, getLogWriter()) 33 | encoder := getEncoder() 34 | level := zap.InfoLevel 35 | if os.Getenv("FETCHIT_DEBUG") != "" { 36 | level = zap.DebugLevel 37 | } 38 | core := zapcore.NewCore(encoder, syncer, zap.NewAtomicLevelAt(level)) 39 | l := zap.New(core, zap.AddCaller()) 40 | logger = l.Sugar() 41 | logger.Debug("Fetchit debug logging enabled.") 42 | } 43 | 44 | func getEncoder() zapcore.Encoder { 45 | cfg := zap.NewProductionEncoderConfig() 46 | // The format time can be customized 47 | cfg.EncodeTime = zapcore.ISO8601TimeEncoder 48 | cfg.EncodeLevel = zapcore.CapitalLevelEncoder 49 | return zapcore.NewConsoleEncoder(cfg) 50 | } 51 | 52 | // Save file log cut 53 | func getLogWriter() zapcore.WriteSyncer { 54 | lumberJackLogger := &lumberjack.Logger{ 55 | Filename: logFile, 56 | MaxSize: 1, // File content size, MB 57 | MaxBackups: 5, // Maximum number of old files retained 58 | MaxAge: 30, // Maximum number of days to keep old files 59 | Compress: false, // Is the file compressed 60 | } 61 | return zapcore.AddSync(lumberJackLogger) 62 | } 63 | -------------------------------------------------------------------------------- /pkg/engine/systemd.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "os" 7 | "path/filepath" 8 | "strconv" 9 | "time" 10 | 11 | "github.com/containers/fetchit/pkg/engine/utils" 12 | "github.com/containers/podman/v4/libpod/define" 13 | "github.com/containers/podman/v4/pkg/specgen" 14 | "github.com/go-git/go-git/v5/plumbing" 15 | "github.com/go-git/go-git/v5/plumbing/object" 16 | "github.com/opencontainers/runtime-spec/specs-go" 17 | ) 18 | 19 | const ( 20 | podmanAutoUpdate = "podman-autoupdate" 21 | podmanAutoUpdateService = "podman-auto-update.service" 22 | podmanAutoUpdateTimer = "podman-auto-update.timer" 23 | podmanServicePath = "/usr/lib/systemd/system" 24 | systemdPathRoot = "/etc/systemd/system" 25 | systemdMethod = "systemd" 26 | systemdImage = "quay.io/fetchit/fetchit-systemd:latest" 27 | ) 28 | 29 | // Systemd to place and/or enable systemd unit files on host 30 | type Systemd struct { 31 | CommonMethod `mapstructure:",squash"` 32 | // If true, will place unit file in /etc/systemd/system/ 33 | // If false (default) will place unit file in ~/.config/systemd/user/ 34 | Root bool `mapstructure:"root"` 35 | // If true, will enable and start all systemd services from fetched unit files 36 | // If true, will reload and restart the services with every scheduled run 37 | // Implies Enable=true, will override Enable=false 38 | Restart bool `mapstructure:"restart"` 39 | // If true, will enable and start systemd services from fetched unit files 40 | // If false (default), will place unit file(s) in appropriate systemd path 41 | Enable bool `mapstructure:"enable"` 42 | autoUpdateAll bool 43 | } 44 | 45 | type PodmanAutoUpdate struct { 46 | // AutoUpdateAll will start podman-auto-update.service, podman-auto-update.timer on the host 47 | // 'podman auto-update' updates all services running podman with the autoupdate label 48 | // see https://docs.podman.io/en/latest/markdown/podman-auto-update.1.html#systemd-unit-and-timer 49 | // TODO: update /etc/systemd/system/podman-auto-update.timer.d/override.conf with schedule 50 | // By default, podman will auto-update at midnight daily when this service is running 51 | Root bool `mapstructure:"root"` 52 | User bool `mapstructure:"user"` 53 | } 54 | 55 | func (p *PodmanAutoUpdate) AutoUpdateSystemd() []*Systemd { 56 | var sysds []*Systemd 57 | if p.Root { 58 | sd := &Systemd{ 59 | Root: true, 60 | autoUpdateAll: true, 61 | // Schedule with Autoupdate is no-op 62 | CommonMethod: CommonMethod{ 63 | Name: podmanAutoUpdate + "-root", 64 | Schedule: "*/1 * * * *", 65 | }, 66 | } 67 | sysds = append(sysds, sd) 68 | } 69 | if p.User { 70 | sd := &Systemd{ 71 | Root: false, 72 | autoUpdateAll: true, 73 | // Schedule with Autoupdate is no-op 74 | CommonMethod: CommonMethod{ 75 | Name: podmanAutoUpdate + "-user", 76 | Schedule: "*/1 * * * *", 77 | }, 78 | } 79 | sysds = append(sysds, sd) 80 | } 81 | return sysds 82 | } 83 | 84 | func (sd *Systemd) GetKind() string { 85 | return systemdMethod 86 | } 87 | 88 | func (sd *Systemd) Process(ctx, conn context.Context, skew int) { 89 | target := sd.GetTarget() 90 | time.Sleep(time.Duration(skew) * time.Millisecond) 91 | target.mu.Lock() 92 | defer target.mu.Unlock() 93 | 94 | if sd.autoUpdateAll && !sd.initialRun { 95 | return 96 | } 97 | tag := []string{".service"} 98 | if sd.Restart { 99 | sd.Enable = true 100 | } 101 | if sd.initialRun { 102 | if sd.autoUpdateAll { 103 | if err := sd.MethodEngine(ctx, conn, nil, ""); err != nil { 104 | logger.Infof("Failed to start podman-auto-update.service: %v", err) 105 | } 106 | sd.initialRun = false 107 | return 108 | } 109 | err := getRepo(target) 110 | if err != nil { 111 | logger.Errorf("Failed to clone repository %s: %v", target.url, err) 112 | return 113 | } 114 | 115 | err = zeroToCurrent(ctx, conn, sd, target, &tag) 116 | if err != nil { 117 | logger.Errorf("Error moving to current: %v", err) 118 | return 119 | } 120 | } 121 | 122 | err := currentToLatest(ctx, conn, sd, target, &tag) 123 | if err != nil { 124 | logger.Errorf("Error moving current to latest: %v", err) 125 | return 126 | } 127 | 128 | sd.initialRun = false 129 | } 130 | 131 | func (sd *Systemd) MethodEngine(ctx context.Context, conn context.Context, change *object.Change, path string) error { 132 | var changeType string = "unknown" 133 | var curr *string = nil 134 | var prev *string = nil 135 | if change != nil { 136 | if change.From.Name != "" { 137 | prev = &change.From.Name 138 | } 139 | if change.To.Name != "" { 140 | curr = &change.To.Name 141 | } 142 | if change.From.Name == "" && change.To.Name != "" { 143 | changeType = "create" 144 | } 145 | if change.From.Name != "" && change.To.Name != "" { 146 | if change.From.Name == change.To.Name { 147 | changeType = "update" 148 | } else { 149 | changeType = "rename" 150 | } 151 | } 152 | if change.From.Name != "" && change.To.Name == "" { 153 | changeType = "delete" 154 | } 155 | } 156 | nonRootHomeDir := os.Getenv("HOME") 157 | if nonRootHomeDir == "" { 158 | return fmt.Errorf("Could not determine $HOME for host, must set $HOME on host machine for non-root systemd method") 159 | } 160 | var dest string 161 | if sd.Root { 162 | dest = systemdPathRoot 163 | } else { 164 | dest = filepath.Join(nonRootHomeDir, ".config", "systemd", "user") 165 | } 166 | if change != nil { 167 | sd.initialRun = true 168 | } 169 | return sd.systemdPodman(ctx, conn, path, dest, prev, curr, &changeType) 170 | } 171 | 172 | func (sd *Systemd) Apply(ctx, conn context.Context, currentState, desiredState plumbing.Hash, tags *[]string) error { 173 | changeMap, err := applyChanges(ctx, sd.GetTarget(), sd.GetTargetPath(), sd.Glob, currentState, desiredState, tags) 174 | if err != nil { 175 | return err 176 | } 177 | if err := runChanges(ctx, conn, sd, changeMap); err != nil { 178 | return err 179 | } 180 | return nil 181 | } 182 | 183 | func (sd *Systemd) systemdPodman(ctx context.Context, conn context.Context, path, dest string, prev *string, curr *string, changeType *string) error { 184 | logger.Infof("Deploying systemd file(s) %s", path) 185 | if sd.autoUpdateAll { 186 | if !sd.initialRun { 187 | return nil 188 | } 189 | if err := sd.enableRestartSystemdService(conn, "autoupdate", dest, podmanAutoUpdateTimer); err != nil { 190 | return utils.WrapErr(err, "Error running systemctl enable --now %s", podmanAutoUpdateTimer) 191 | } 192 | return sd.enableRestartSystemdService(conn, "autoupdate", dest, podmanAutoUpdateService) 193 | } 194 | if sd.initialRun { 195 | ft := &FileTransfer{ 196 | CommonMethod: CommonMethod{ 197 | Name: sd.Name, 198 | }, 199 | } 200 | if err := ft.fileTransferPodman(ctx, conn, path, dest, prev); err != nil { 201 | return utils.WrapErr(err, "Error deploying systemd %s file(s), Path: %s", sd.Name, sd.TargetPath) 202 | } 203 | } 204 | if !sd.Enable { 205 | logger.Infof("Systemd target %s successfully processed", sd.Name) 206 | return nil 207 | } 208 | if *changeType == "create" { 209 | return sd.enableRestartSystemdService(conn, "enable", dest, filepath.Base(*curr)) 210 | } 211 | if *changeType == "update" { 212 | if sd.Restart { 213 | return sd.enableRestartSystemdService(conn, "restart", dest, filepath.Base(*curr)) 214 | } else { 215 | return sd.enableRestartSystemdService(conn, "enable", dest, filepath.Base(*curr)) 216 | } 217 | } 218 | if *changeType == "rename" { 219 | if err := sd.enableRestartSystemdService(conn, "stop", dest, filepath.Base(*prev)); err != nil { 220 | return err 221 | } 222 | return sd.enableRestartSystemdService(conn, "enable", dest, filepath.Base(*curr)) 223 | } 224 | if *changeType == "delete" { 225 | return sd.enableRestartSystemdService(conn, "stop", dest, filepath.Base(*prev)) 226 | } 227 | logger.Infof("Systemd target %s %s not processed", sd.Name, *changeType) 228 | return nil 229 | } 230 | 231 | func (sd *Systemd) enableRestartSystemdService(conn context.Context, action, dest, service string) error { 232 | act := action 233 | if action == "autoupdate" { 234 | act = "enable" 235 | } 236 | logger.Infof("Systemd target: %s, running systemctl %s %s", sd.Name, act, service) 237 | if err := detectOrFetchImage(conn, systemdImage, false); err != nil { 238 | return err 239 | } 240 | 241 | // TODO: remove 242 | if sd.Root { 243 | os.Setenv("ROOT", "true") 244 | } else { 245 | os.Setenv("ROOT", "false") 246 | } 247 | s := specgen.NewSpecGenerator(systemdImage, false) 248 | runMounttmp := "/run" 249 | runMountsd := "/run/systemd" 250 | runMountc := "/sys/fs/cgroup" 251 | xdg := "" 252 | if !sd.Root { 253 | // need to document this for non-root usage 254 | // can't use user.Current because always root in fetchit container 255 | xdg = os.Getenv("XDG_RUNTIME_DIR") 256 | if xdg == "" { 257 | xdg = "/run/user/1000" 258 | } 259 | runMountsd = xdg + "/systemd" 260 | runMounttmp = xdg 261 | } 262 | s.Privileged = true 263 | s.PidNS = specgen.Namespace{ 264 | NSMode: "host", 265 | Value: "", 266 | } 267 | if action == "autoupdate" { 268 | s.Mounts = []specs.Mount{{Source: podmanServicePath, Destination: podmanServicePath, Type: define.TypeBind, Options: []string{"rw"}}, {Source: dest, Destination: dest, Type: define.TypeBind, Options: []string{"rw"}}, {Source: runMounttmp, Destination: runMounttmp, Type: define.TypeTmpfs, Options: []string{"rw"}}, {Source: runMountc, Destination: runMountc, Type: define.TypeBind, Options: []string{"ro"}}, {Source: runMountsd, Destination: runMountsd, Type: define.TypeBind, Options: []string{"rw"}}} 269 | } else { 270 | s.Mounts = []specs.Mount{{Source: dest, Destination: dest, Type: define.TypeBind, Options: []string{"rw"}}, {Source: runMounttmp, Destination: runMounttmp, Type: define.TypeTmpfs, Options: []string{"rw"}}, {Source: runMountc, Destination: runMountc, Type: define.TypeBind, Options: []string{"ro"}}, {Source: runMountsd, Destination: runMountsd, Type: define.TypeBind, Options: []string{"rw"}}} 271 | } 272 | s.Name = "systemd-" + act + "-" + service + "-" + sd.Name 273 | envMap := make(map[string]string) 274 | envMap["ROOT"] = strconv.FormatBool(sd.Root) 275 | envMap["SERVICE"] = service 276 | envMap["ACTION"] = act 277 | envMap["HOME"] = os.Getenv("HOME") 278 | if !sd.Root { 279 | envMap["XDG_RUNTIME_DIR"] = xdg 280 | } 281 | s.Env = envMap 282 | createResponse, err := createAndStartContainer(conn, s) 283 | if err != nil { 284 | return err 285 | } 286 | 287 | err = waitAndRemoveContainer(conn, createResponse.ID) 288 | if err != nil { 289 | return err 290 | } 291 | logger.Infof("Systemd target %s-%s %s complete", sd.Name, act, service) 292 | return nil 293 | } 294 | -------------------------------------------------------------------------------- /pkg/engine/types.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "context" 5 | "sync" 6 | 7 | "github.com/go-co-op/gocron" 8 | "github.com/go-git/go-git/v5/plumbing" 9 | "github.com/go-git/go-git/v5/plumbing/object" 10 | ) 11 | 12 | type Method interface { 13 | GetName() string 14 | GetKind() string 15 | GetTarget() *Target 16 | Process(ctx context.Context, conn context.Context, skew int) 17 | Apply(ctx context.Context, conn context.Context, currentState plumbing.Hash, desiredState plumbing.Hash, tags *[]string) error 18 | MethodEngine(ctx context.Context, conn context.Context, change *object.Change, path string) error 19 | } 20 | 21 | // FetchitConfig requires necessary objects to process targets 22 | type FetchitConfig struct { 23 | GitAuth *GitAuth `mapstructure:"gitAuth"` 24 | TargetConfigs []*TargetConfig `mapstructure:"targetConfigs"` 25 | ConfigReload *ConfigReload `mapstructure:"configReload"` 26 | Prune *Prune `mapstructure:"prune"` 27 | PodmanAutoUpdate *PodmanAutoUpdate `mapstructure:"podmanAutoUpdate"` 28 | Images []*Image `mapstructure:"images"` 29 | conn context.Context 30 | scheduler *gocron.Scheduler 31 | } 32 | 33 | type TargetConfig struct { 34 | Name string `mapstructure:"name"` 35 | Url string `mapstructure:"url"` 36 | Device string `mapstructure:"device"` 37 | Disconnected bool `mapstructure:"disconnected"` 38 | VerifyCommitsInfo *VerifyCommitsInfo `mapstructure:"verifyCommitsInfo"` 39 | Branch string `mapstructure:"branch"` 40 | Ansible []*Ansible `mapstructure:"ansible"` 41 | FileTransfer []*FileTransfer `mapstructure:"filetransfer"` 42 | Kube []*Kube `mapstructure:"kube"` 43 | Raw []*Raw `mapstructure:"raw"` 44 | Systemd []*Systemd `mapstructure:"systemd"` 45 | 46 | image *Image 47 | prune *Prune 48 | configReload *ConfigReload 49 | mu sync.Mutex 50 | } 51 | 52 | type Target struct { 53 | ssh bool 54 | sshKey string 55 | url string 56 | pat string 57 | envSecret string 58 | username string 59 | password string 60 | device string 61 | localPath string 62 | branch string 63 | mu sync.Mutex 64 | disconnected bool 65 | gitsignVerify bool 66 | gitsignRekorURL string 67 | } 68 | 69 | type SchedInfo struct { 70 | schedule string 71 | skew *int 72 | } 73 | 74 | type VerifyCommitsInfo struct { 75 | // sigstore/gitsign verification with Rekor is available 76 | // add other verification options as necessary 77 | GitsignVerify bool 78 | // default is https://rekor.sigstore.dev 79 | GitsignRekorURL string 80 | } 81 | -------------------------------------------------------------------------------- /pkg/engine/utils/errors.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import "fmt" 4 | 5 | func WrapErr(e error, msg string, args ...interface{}) error { 6 | final_msg := fmt.Sprintf(msg, args...) 7 | return fmt.Errorf("%s: %s", final_msg, e) 8 | } 9 | -------------------------------------------------------------------------------- /pkg/engine/utils/errors_test.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "errors" 5 | "testing" 6 | ) 7 | 8 | func TestWrapErr(t *testing.T) { 9 | msg := "Error" 10 | e := errors.New("other_err") 11 | err := WrapErr(e, msg).Error() 12 | expected := "Error: other_err" 13 | if err != expected { 14 | t.Fatalf("Failed: err: %s != %s", err, expected) 15 | } 16 | 17 | msg = "Error %s" 18 | e = errors.New("other_err") 19 | err = WrapErr(e, msg, "test").Error() 20 | expected = "Error test: other_err" 21 | if err != expected { 22 | t.Fatalf("Failed: err: %s != %s", err, expected) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /pkg/engine/utils/util.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/containers/podman/v4/pkg/bindings/images" 7 | ) 8 | 9 | func FetchImage(conn context.Context, image string) error { 10 | present, err := images.Exists(conn, image, nil) 11 | if err != nil { 12 | return err 13 | } 14 | 15 | if !present { 16 | _, err = images.Pull(conn, image, nil) 17 | if err != nil { 18 | return err 19 | } 20 | } 21 | return nil 22 | } 23 | -------------------------------------------------------------------------------- /scripts/entry.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e -o pipefail 3 | 4 | 5 | main() { 6 | echo "initializing fetchit" 7 | if [[ -n "${FETCHIT_CONFIG}" ]]; then 8 | declare fetchitConfigFile='/opt/mount/config.yaml' 9 | echo "detected config environment variable" 10 | if ! [ -d '/opt/mount' ]; then 11 | echo "/opt/mount doesn't exist, creating" 12 | mkdir -p /opt/mount 13 | fi 14 | 15 | if [ -f "${fetchitConfigFile}" ]; then 16 | echo 'overriding config with variable' 17 | fi 18 | echo "${FETCHIT_CONFIG}" > "${fetchitConfigFile}" 19 | echo "wrote new config to ${fetchitConfigFile}" 20 | fi 21 | 22 | echo 'starting fetchit' 23 | /usr/local/bin/fetchit start 24 | } 25 | 26 | main -------------------------------------------------------------------------------- /systemd/fetchit-root.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Fetchit container management tool 3 | Documentation=man:podman-generate-systemd(1) 4 | Wants=network-online.target 5 | After=network-online.target 6 | RequiresMountsFor=%t/containers 7 | 8 | [Service] 9 | Environment=PODMAN_SYSTEMD_UNIT=%n 10 | Restart=always 11 | TimeoutStopSec=65 12 | ExecStartPre=/usr/bin/mkdir -p %h/.fetchit 13 | ExecStartPre=/bin/rm -f %t/%n.ctr-id 14 | ExecStart=/usr/bin/podman run --cidfile=%t/%n.ctr-id --cgroups=no-conmon --rm --security-opt label=disable --sdnotify=conmon --replace --label io.containers.autoupdate=registry -d --name fetchit -v fetchit-volume:/opt -v %h/.fetchit:/opt/mount -v /run/podman/podman.sock:/run/podman/podman.sock quay.io/fetchit/fetchit:latest 15 | ExecStop=/usr/bin/podman stop --ignore --cidfile=%t/%n.ctr-id 16 | ExecStopPost=/usr/bin/podman rm -f --ignore --cidfile=%t/%n.ctr-id 17 | Type=notify 18 | NotifyAccess=all 19 | 20 | [Install] 21 | WantedBy=default.target 22 | -------------------------------------------------------------------------------- /systemd/fetchit-user.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Fetchit container management tool 3 | Documentation=man:podman-generate-systemd(1) 4 | Wants=network-online.target 5 | After=network-online.target 6 | RequiresMountsFor=%t/containers 7 | 8 | [Service] 9 | Environment=PODMAN_SYSTEMD_UNIT=%n 10 | Restart=always 11 | TimeoutStopSec=65 12 | ExecStartPre=/usr/bin/mkdir -p %h/.fetchit 13 | ExecStartPre=/bin/rm -f %t/%n.ctr-id 14 | ExecStart=/usr/bin/podman run --cidfile=%t/%n.ctr-id --cgroups=no-conmon --rm --security-opt label=disable --sdnotify=conmon --replace --label io.containers.autoupdate=registry -d --name fetchit -v fetchit-volume:/opt -v %h/.fetchit:/opt/mount -v /run/user/%U/podman/podman.sock:/run/podman/podman.sock -e XDG_RUNTIME_DIR="/run/user/%U" -e HOME=%h quay.io/fetchit/fetchit:latest 15 | ExecStop=/usr/bin/podman stop --ignore --cidfile=%t/%n.ctr-id 16 | ExecStopPost=/usr/bin/podman rm -f --ignore --cidfile=%t/%n.ctr-id 17 | Type=notify 18 | NotifyAccess=all 19 | 20 | [Install] 21 | WantedBy=default.target 22 | --------------------------------------------------------------------------------