├── .gitignore ├── .travis.yml ├── COPYING ├── Makefile ├── README.md ├── doc ├── conf.py ├── images │ └── fmu_logo.png ├── index.rst └── src │ ├── add-targets-to-hawkbit.md │ ├── bootup.md │ ├── classes.rst │ └── fullmetalupdate.rst ├── fullmetalupdate.py ├── fullmetalupdate ├── __init__.py ├── fullmetalupdate_ddi_client.py └── updater.py ├── rauc_hawkbit ├── __init__.py ├── config.cfg ├── dbus_client.py ├── ddi │ ├── __init__.py │ ├── cancel_action.py │ ├── client.py │ ├── deployment_base.py │ └── softwaremodules.py └── rauc_dbus_ddi_client.py └── scripts └── send_feedback.sh /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *__pycache__ 3 | .*.swp 4 | .cache 5 | /MANIFEST 6 | .tox 7 | /.#tox.ini 8 | /.eggs/README.txt 9 | *.egg 10 | *.egg-info 11 | /venv* 12 | /build 13 | /doc/.build 14 | /doc/modules 15 | /.coverage 16 | /dist 17 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | sudo: false 3 | python: 4 | - "3.5" 5 | - "3.6" 6 | install: 7 | - pip install --upgrade pytest pytest-mock pytest-cov codecov 8 | - pip install tox-travis 9 | - pip install sphinx sphinx_rtd_theme 10 | - pip install aiohttp 11 | script: 12 | - tox 13 | - python setup.py build_sphinx 14 | after_success: 15 | - codecov 16 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 489 | 490 | Also add information on how to contact you by electronic and paper mail. 491 | 492 | You should also get your employer (if you work as a programmer) or your 493 | school, if any, to sign a "copyright disclaimer" for the library, if 494 | necessary. Here is a sample; alter the names: 495 | 496 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 497 | library `Frob' (a library for tweaking knobs) written by James Random Hacker. 498 | 499 | , 1 April 1990 500 | Ty Coon, President of Vice 501 | 502 | That's all there is to it! 503 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = doc 9 | BUILDDIR = sphinx 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | FullMetalUpdate is a Python application that handles update for the System on which it is running. 4 | 5 | To get started, check the documentation: 6 | [Get Started](https://www.fullmetalupdate.io/docs/documentation/) 7 | 8 | # How to generate documentation about the project 9 | FullMetalUpdate is now documented as a Sphinx Project, which allow you to generate the documentation locally. 10 | Please follow the commands below. 11 | 12 | ``` 13 | sudo apt-get install ostree gir1.2-ostree-1.0 14 | pip install pydbus aiohttp sphinx sphinx-rtd-theme recommonmark 15 | 16 | make html 17 | firefox sphinx/html/index.html 18 | ``` 19 | # Contribute 20 | 21 | See [Contribute](https://www.fullmetalupdate.io/docs/contribute/) 22 | 23 | # Contact us 24 | 25 | * Want to chat with the team behind the dockerfiles for FMU? [Chat room](https://gitter.im/fullmetalupdate/community). 26 | * Having issues with FullMetalUpdate? Open a [GitHub issue](https://github.com/FullMetalUpdate/fullmetalupdate/issues). 27 | * You can also check out our [Project Homepage](https://www.fullmetalupdate.io/) for further contact options. 28 | 29 | -------------------------------------------------------------------------------- /doc/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # This file only contains a selection of the most common options. For a full 4 | # list see the documentation: 5 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 6 | 7 | # -- Path setup -------------------------------------------------------------- 8 | 9 | # If extensions (or modules to document with autodoc) are in another directory, 10 | # add these directories to sys.path here. If the directory is relative to the 11 | # documentation root, use os.path.abspath to make it absolute, like shown here. 12 | # 13 | import os 14 | import sys 15 | 16 | from recommonmark.parser import CommonMarkParser 17 | 18 | sys.path.insert(0, os.path.abspath('.')) 19 | sys.path.insert(0, os.path.abspath('../')) 20 | sys.path.insert(0, os.path.abspath('../fullmetalupdate/')) 21 | sys.path.insert(0, os.path.abspath('../rauc_hawkbit/')) 22 | sys.path.insert(0, os.path.abspath('../scripts/')) 23 | 24 | 25 | # -- Project information ----------------------------------------------------- 26 | 27 | project = 'FullMetalUpdate' 28 | copyright = '2021, Witekio' 29 | author = 'Witekio' 30 | 31 | # The full version, including alpha/beta/rc tags 32 | release = '2.0' 33 | 34 | 35 | # -- General configuration --------------------------------------------------- 36 | 37 | # Add any Sphinx extension module names here, as strings. They can be 38 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 39 | # ones. 40 | extensions = [ 41 | 'sphinx.ext.autodoc' 42 | ] 43 | 44 | # Add any paths that contain templates here, relative to this directory. 45 | templates_path = ['_templates'] 46 | 47 | # List of patterns, relative to source directory, that match files and 48 | # directories to ignore when looking for source files. 49 | # This pattern also affects html_static_path and html_extra_path. 50 | exclude_patterns = [] 51 | 52 | 53 | # -- Options for HTML output ------------------------------------------------- 54 | 55 | # The theme to use for HTML and HTML Help pages. See the documentation for 56 | # a list of builtin themes. 57 | # 58 | html_theme = 'sphinx_rtd_theme' 59 | 60 | # Add any paths that contain custom static files (such as style sheets) here, 61 | # relative to this directory. They are copied after the builtin static files, 62 | # so a file named "default.css" will overwrite the builtin "default.css". 63 | html_static_path = ['_static'] 64 | 65 | # Allow to use both .md (Markdown) and .rst (reST) files within the sphinx project. 66 | 67 | source_suffix = ['.rst', '.md'] 68 | 69 | source_parsers = { 70 | '.md': CommonMarkParser, 71 | } 72 | -------------------------------------------------------------------------------- /doc/images/fmu_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FullMetalUpdate/fullmetalupdate/8135496159cc6f2b7c1cd87f6b92a0f23e22b591/doc/images/fmu_logo.png -------------------------------------------------------------------------------- /doc/index.rst: -------------------------------------------------------------------------------- 1 | .. FullMetalUpdate documentation master file, created by 2 | sphinx-quickstart on Thu May 27 11:11:14 2021. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | .. Logo_FMU: 7 | .. figure:: ./images/fmu_logo.png 8 | :align: center 9 | :alt: logo 10 | 11 | FullMetalUpdate is a Python application that handles update for the System on which it is running. 12 | 13 | Get started with your own board on `FullMetalUpdate Official Tutorial `_. 14 | 15 | Architecture 16 | ============= 17 | 18 | SOON 19 | 20 | .. toctree:: 21 | :maxdepth: 2 22 | :glob: 23 | 24 | FMU Client API 25 | ================= 26 | .. toctree:: 27 | :maxdepth: 2 28 | :glob: 29 | 30 | ./src/classes.rst 31 | ./src/fullmetalupdate.rst 32 | 33 | Technical documentation 34 | ========================== 35 | .. toctree:: 36 | :maxdepth: 2 37 | :glob: 38 | 39 | ./src/bootup.md 40 | ./src/add-targets-to-hawkbit.md 41 | 42 | | See the `Rollback Feature `_ documentation on Github. 43 | | See `Benchmark on FullMetalUpdate `_ on Github. 44 | 45 | More documentation incoming on `FullMetalUpdate Documentation `_ Github. 46 | 47 | Contribute 48 | ============== 49 | | Please see `FullMetalUpdate `_ Github. 50 | | Please see our `directives `_ on how to contribute. 51 | 52 | Contact us 53 | =========== 54 | * Want to chat with the team behind the dockerfiles for FMU? `Chat room `_. 55 | * Having issues with FullMetalUpdate? Open a `GitHub issue `_. 56 | * You can also check out our `Project Homepage `_ for further contact options. 57 | -------------------------------------------------------------------------------- /doc/src/add-targets-to-hawkbit.md: -------------------------------------------------------------------------------- 1 | How to add targets to Hawkbit 2 | ================================== 3 | 4 | When using FullMetalUpdate, you may require to work on multiple targets and deploy OSes or 5 | containers on them. In this document, we will go though the steps required to add a new 6 | target on Hawkbit and be able to deploy images on any of them. 7 | 8 | Adding the target on Hawkbit's UI 9 | ------------------------------------ 10 | 11 | 1. Go to the cloud directory where Hawkbit is launched (`fullmetalupdate-cloud-demo`) 12 | 13 | 2. Edit `ConfigureServer.sh` and make the following changes : 14 | - copy the first paragraph of the file, beginning with `# Set up a target...`, and 15 | paste it right afterwards 16 | - change `securityToken`, `controllerId` and `name`. For the last two, pick whatever 17 | you want. For the token, also pick whatever you want, or you can generate a token 18 | using `date | md5sum`, assuming you're on Linux. 19 | 20 | 3. Exit, and execute `./ConfigureServer.sh` (the server needs to be running). 21 | 22 | 4. You should see a new target pop up on Hawkbit. Cross-check that the credentials you 23 | typed at the last step are correct in the information panel of the target. 24 | 25 | Configuring your build to connect your target with Hawkbit 26 | --------------------------------------------------------------- 27 | 28 | There are two ways to make your change on Hawkbit take effect or the target : 29 | 30 | - (*Recommended*) Configure the new credentials from the build directory. 31 | These changes will be permanent though all the next updates of your target 32 | 33 | - Configure the new credentials on the target directly 34 | 35 | If you already deployed your target, we recommend to go thourhg both ways. 36 | 37 | Configuring a new target on the build system 38 | --------------------------------------------------- 39 | 40 | Before proceeding further, **close any instanciation of the build-yocto docker** (any 41 | `./Startbuild.sh bash *`). 42 | 43 | 1. Go to your Yocto directory (`fullmetalupdate-yocto-demo`). 44 | 45 | 2. Edit the `config.cfg.sample` and make the following changes : 46 | 47 | Fill in `hawkbit_target_name` and `hawkbit_auth_token` using what you have previously 48 | defined (`controllerId` and `securityToken`). 49 | 50 | 3. Exit, and execute `bash ConfigureBuild.sh`. 51 | 52 | 4. Execute `./Startbuild.sh fullmetalupdate-os`. It should build the fullmetalupdate 53 | client again. Then you can flash the new image to your target, which will contain the 54 | new credentials. 55 | 56 | 5. After starting the target, you should see your device's IP in the target's information panel. 57 | 58 | Configuring the credentials from the target 59 | -------------------------------------------------- 60 | 61 | *Note* : these changes will be permanent only if you made the changes on the build system as described in the last section. Otherwise, the following changes will be lost on the next OS update. 62 | 63 | If you have already deployed your target and have remote access to it, please follow these steps : 64 | 65 | 1. Remount `/usr` as read-write by executing: `mount -o remount,rw /usr`. 66 | 67 | 2. Edit the configuration file by executing `vi 68 | /usr/fullmetalupdate/rauc_hawkbit/config.cfg`. 69 | 70 | 3. Fill in `hawkbit_target_name` and `hawkbit_auth_token` using what you have previously 71 | defined (`controllerId` and `securityToken`). 72 | 73 | 4. Restart the FullMetalUpdate client by executing `systemctl restart fullmetalupdate`. 74 | 75 | 5. You should see your device's IP in the target's information panel. 76 | -------------------------------------------------------------------------------- /doc/src/bootup.md: -------------------------------------------------------------------------------- 1 | Booting sequence in the case of FullMetalUpdate 2 | ======================================================== 3 | 4 | 1. **Primary processor steps :** 5 | 6 | 1. Primary bootstrap to initialize interrupt/exception vectors, clocks and RAM 7 | 2. **U-boot** is decompressed and loaded into the RAM 8 | 3. Execution is passed to U-boot 9 | 10 | 2. **U-boot boot sequence :** 11 | 12 | 1. Flash, serial console, Ethernet MAC Address (etc.) are configured 13 | 2. A minimal bootscript called `boot.scr` is executed and is used only to load a 14 | **custom** script called `uEnv.txt`, written by us. These two scripts (the minimal 15 | one and the custom one) are both defined in `meta-fullmetalupdate-extra `_ in the dynamic-layers folder. What those files contain and how they are handled is specific to the board, but they will 16 | serve the same purpose. 17 | 3. The custom `uEnv.txt` u-boot script does several things : 18 | - It defines the proper storage interfaces and addresses (`bootmmc`, `bootiaddr`…) 19 | - It defines multiple boot commands (`bootcmd*`) which all serve different purposes : 20 | - `bootcmd` is the main boot command : it contains conditional branches used to 21 | boot either onto the current deployment or the rollback deployment. It also 22 | execute the ostree boot command `bootcmd_otenv` 23 | - `bootcmd_otenv` is used to load OStree environment variables, needed by 24 | OStree to boot on the proper deployment. Note that this command imports 25 | theses variables from **another `uEnv.txt`** which **totally differs** from 26 | our custom one, defined in Yocto. This `uEnv.txt` is defined in 27 | `/boot/loader/uEnv.txt` and written by OSTree when staging commits. Please 28 | see the `OSTree documentation `_ for more info. 29 | - When this script runs, it will execute these different commands and the 30 | kernel, ramdisk image, device tree blob will be loaded. The execution is then 31 | passed to the kernel. 32 | 33 | 3. **Kernel boot sequence :** 34 | 35 | The kernel initializes the various components/drivers of the target. 36 | 37 | *Note :* 38 | The typical kernel command line looks like this (on the IMX8) : 39 | 40 | `rw rootwait console=ttymxc0,115200 ostree=/ostree/boot.0/poky//0 41 | ostree_root=/dev/mmcblk1p2 root=/dev/ram0 ramdisk_size=8192 rw rootfstype=ext4 42 | consoleblank=0 vt.global_cursor_default=0 video=mxcfb0:dev=ldb,bpp=32,if=RGB32`, 43 | where `` is the current deployment's hash. 44 | 45 | It contains interesting arguments such as the `ostree=` which is parsed by OSTree to determine the current deployment. 46 | 47 | 4. **OSTree initrd script :** 48 | 49 | OSTree has a custom initrd script since the file system is a bit different on OSTree 50 | devices (see `the ostree documentation `_). The script mounts the 51 | different file systems and determines the current deployment by parsing the kernel 52 | command line. 53 | 54 | More details this script are found in the `meta-updater ` layer. 55 | 56 | 5. **systemd :** 57 | 58 | systemd, the init manager, does his usual job : starting the usual target units, but also start the FullMetalUpdate client with a custom service file (which is found `here `_). 59 | 60 | 6. **Client initialization :** 61 | 62 | The client initializes the container ostree repo and starts the different preinstalled 63 | containers. 64 | 65 | **Useful resources :** 66 | - `man bootup`, `man boot`, `man bootparams` 67 | - https://ostree.readthedocs.io/ 68 | - https://www.denx.de/wiki/U-Boot/Documentation 69 | -------------------------------------------------------------------------------- /doc/src/classes.rst: -------------------------------------------------------------------------------- 1 | Updater Class 2 | ============== 3 | .. autoclass:: updater.AsyncUpdater 4 | :members: 5 | 6 | FullMetalUpdateDDIClient Class 7 | ================================ 8 | .. autoclass:: fullmetalupdate_ddi_client.FullMetalUpdateDDIClient 9 | :members: -------------------------------------------------------------------------------- /doc/src/fullmetalupdate.rst: -------------------------------------------------------------------------------- 1 | FullMetalUpdate Client 2 | ======================== 3 | -------------------------------------------------------------------------------- /fullmetalupdate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | from configparser import ConfigParser 5 | from pathlib import Path 6 | import logging 7 | import argparse 8 | import asyncio 9 | import aiohttp 10 | from distutils.util import strtobool 11 | from fullmetalupdate.fullmetalupdate_ddi_client import FullMetalUpdateDDIClient 12 | 13 | 14 | async def main(): 15 | # config parsing 16 | config = ConfigParser() 17 | parser = argparse.ArgumentParser() 18 | parser.add_argument( 19 | '-c', 20 | '--config', 21 | type=str, 22 | help="config file") 23 | parser.add_argument( 24 | '-d', 25 | '--debug', 26 | action='store_true', 27 | default=False, 28 | help="enable debug mode" 29 | ) 30 | 31 | args = parser.parse_args() 32 | 33 | if not args.config: 34 | args.config = 'config.cfg' 35 | 36 | cfg_path = Path(args.config) 37 | 38 | if not cfg_path.is_file(): 39 | print("Cannot read config file '{}'".format(cfg_path.name)) 40 | exit(1) 41 | 42 | config.read_file(cfg_path.open()) 43 | 44 | try: 45 | LOG_LEVEL = { 46 | 'debug': logging.DEBUG, 47 | 'info': logging.INFO, 48 | 'warn': logging.WARN, 49 | 'error': logging.ERROR, 50 | 'fatal': logging.FATAL, 51 | }[config.get('client', 'log_level').lower()] 52 | except Exception: 53 | LOG_LEVEL = logging.INFO 54 | 55 | local_domain_name = config.get('server', 'server_host_name') 56 | 57 | HOST = local_domain_name + ":" + config.get('client', 'hawkbit_url_port') 58 | SSL = config.getboolean('client', 'hawkbit_ssl') 59 | TENANT_ID = config.get('client', 'hawkbit_tenant_id') 60 | TARGET_NAME = config.get('client', 'hawkbit_target_name') 61 | AUTH_TOKEN = config.get('client', 'hawkbit_auth_token') 62 | ATTRIBUTES = {'FullMetalUpdate': config.get('client', 'hawkbit_target_name')} 63 | 64 | if strtobool(config.get('ostree', 'ostree_ssl')): 65 | url_type = 'https://' 66 | else: 67 | url_type = 'http://' 68 | 69 | OSTREE_REMOTE_ATTRIBUTES = {'name': config.get('ostree', 'ostree_name_remote'), 70 | 'gpg-verify': strtobool(config.get('ostree', 'ostree_gpg-verify')), 71 | 'url': url_type + local_domain_name + ":" + config.get('ostree', 'ostree_url_port')} 72 | 73 | if args.debug: 74 | LOG_LEVEL = logging.DEBUG 75 | 76 | logging.basicConfig(level=LOG_LEVEL, 77 | format='%(asctime)s %(levelname)-8s %(message)s', 78 | datefmt='%Y-%m-%d %H:%M:%S') 79 | 80 | async with aiohttp.ClientSession() as session: 81 | client = FullMetalUpdateDDIClient(session, HOST, SSL, TENANT_ID, TARGET_NAME, 82 | AUTH_TOKEN, ATTRIBUTES) 83 | 84 | if not client.init_checkout_existing_containers(): 85 | client.logger.info("There is no containers pre-installed on the target") 86 | 87 | if not client.init_ostree_remotes(OSTREE_REMOTE_ATTRIBUTES): 88 | client.logger.error("Cannot initialize OSTree remote from config file '{}'".format(cfg_path.name)) 89 | else: 90 | await client.start_polling() 91 | 92 | if __name__ == '__main__': 93 | # create event loop, open aiohttp client session and start polling 94 | loop = asyncio.get_event_loop() 95 | loop.run_until_complete(main()) 96 | -------------------------------------------------------------------------------- /fullmetalupdate/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FullMetalUpdate/fullmetalupdate/8135496159cc6f2b7c1cd87f6b92a0f23e22b591/fullmetalupdate/__init__.py -------------------------------------------------------------------------------- /fullmetalupdate/fullmetalupdate_ddi_client.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from datetime import datetime, timedelta 4 | import os 5 | import os.path 6 | import re 7 | import logging 8 | import json 9 | from threading import Lock, Thread 10 | import socket as s 11 | import subprocess 12 | import asyncio 13 | import gi 14 | 15 | from fullmetalupdate.updater import AsyncUpdater 16 | from rauc_hawkbit.ddi.client import DDIClient, APIError 17 | from rauc_hawkbit.ddi.client import ( 18 | ConfigStatusExecution, ConfigStatusResult) 19 | from rauc_hawkbit.ddi.deployment_base import ( 20 | DeploymentStatusExecution, DeploymentStatusResult) 21 | from rauc_hawkbit.ddi.cancel_action import ( 22 | CancelStatusExecution, CancelStatusResult) 23 | from aiohttp.client_exceptions import ClientOSError, ClientResponseError 24 | 25 | PATH_REBOOT_DATA = '/var/local/fullmetalupdate/reboot_data.json' 26 | DIR_NOTIFY_SOCKET = '/tmp/fullmetalupdate/' 27 | 28 | 29 | class FullMetalUpdateDDIClient(AsyncUpdater): 30 | """ 31 | Client broker communicating via DBUS and HawkBit DDI HTTP interface. Inherits from AsyncUpdater Class. 32 | 33 | :param logging logger: Logger used to print information regarding the update proceedings or to report errors. 34 | :param DDIClient ddi: Client enabling easy GET / POST / PUT request to Hawkbit Server. 35 | :param int action_id: Unique identifier of an Hawkbit update. 36 | :param list feedbackThreads: List of feedback threads to make accesses easier. 37 | :param dictionnary feedbackResults: Each feedback thread is associated with a status_update and a message, which describes if 38 | the starting process of the associated container went well or not. 39 | feedbackResults = {container-sd-notify : {status_result : ... , msg : ...}} 40 | :param Lock mutexResults: Mutex that protects feedbackResults from concurrent accesses (accesses from main thread and accesses 41 | from feedback threads). 42 | """ 43 | 44 | def __init__(self, session, host, ssl, tenant_id, target_name, auth_token, attributes): 45 | """ Constructor of FullMetalUpdateDDIClient Class. 46 | """ 47 | super(FullMetalUpdateDDIClient, self).__init__() 48 | 49 | self.attributes = attributes 50 | 51 | self.logger = logging.getLogger('fullmetalupdate_hawkbit') 52 | self.ddi = DDIClient(session, host, ssl, auth_token, tenant_id, target_name) 53 | self.action_id = None 54 | self.feedbackThreads = [] 55 | self.feedbackResults = None 56 | self.mutexResults = Lock() 57 | 58 | os.makedirs(os.path.dirname(PATH_REBOOT_DATA), exist_ok=True) 59 | os.makedirs(DIR_NOTIFY_SOCKET, exist_ok=True) 60 | 61 | async def start_polling(self, wait_on_error=60): 62 | """ 63 | Wrapper around self.poll_base_resource() for exception handling. 64 | 65 | :param int wait_on_error: Timeout before retry on polling failled 66 | """ 67 | 68 | while True: 69 | try: 70 | await self.poll_base_resource() 71 | except asyncio.CancelledError: 72 | self.logger.info('Polling cancelled') 73 | break 74 | except asyncio.TimeoutError: 75 | self.logger.warning('Polling failed due to TimeoutError') 76 | except (APIError, TimeoutError, ClientOSError, ClientResponseError) as e: 77 | # log error and start all over again 78 | self.logger.warning('Polling failed with a temporary error: {}'.format(e)) 79 | except Exception: 80 | self.logger.exception('Polling failed with an unexpected exception:') 81 | self.action_id = None 82 | self.logger.info('Retry will happen in {} seconds'.format( 83 | wait_on_error)) 84 | await asyncio.sleep(wait_on_error) 85 | 86 | async def identify(self): 87 | """ 88 | Identify target against HawkBit. 89 | """ 90 | 91 | self.logger.info('Sending identifying information to HawkBit') 92 | # identify 93 | await self.ddi.configData(ConfigStatusExecution.closed, 94 | ConfigStatusResult.success, **self.attributes) 95 | 96 | async def cancel(self, base): 97 | """ 98 | Acknoledges cancelation request, retrives ID of Hawkbit update to be cancelled, cancels the relevant Hawkbit update 99 | and finally notify the Hawkbit server about the result of the cancelation process. 100 | 101 | TODO : Implement Hawkbit Update cancelation (this method does not seem to do what it is meant to do) 102 | 103 | :param dictionnary base: Dictionnary storing information about a Hawkbit update. 104 | """ 105 | self.logger.info('Received cancelation request') 106 | # retrieve action id from URL 107 | deployment = base['_links']['cancelAction']['href'] 108 | match = re.search('/cancelAction/(.+)$', deployment) 109 | action_id, = match.groups() 110 | # retrieve stop_id 111 | stop_info = await self.ddi.cancelAction[action_id]() 112 | stop_id = stop_info['cancelAction']['stopId'] 113 | # Reject cancel request 114 | self.logger.info('Rejecting cancelation request') 115 | await self.ddi.cancelAction[stop_id].feedback( 116 | CancelStatusExecution.rejected, 117 | CancelStatusResult.success, 118 | status_details=("Cancelling not supported",)) 119 | 120 | async def process_deployment(self, base): 121 | """ 122 | This method performs a Hawkbit update in several steps : 123 | - Retrieves information about the Hawkbit update based on base dictionnary ; 124 | - Notifies Hawkbit server about the appropriate start of the update ; 125 | - All chunks are then parsed and processed, ie 126 | 1) OS chunks cause a system update (see update_system method) and a system reboot ; 127 | 2) Apps chunks cause apps updates (see update_container method). An app / container that implements the notify feature of systemd is 128 | associated with a feedback thread, which monitors its execution and feedbacks the FMU client if the app succesfully started or not; 129 | - Systemd dependency tree is regenerated in order to take into account every change in service files (new service files or updated 130 | service files), including new dependencies, changes in startup scripts, etc ; 131 | - Containers are then restarted ; 132 | - Finally, Hawkbit server is notified with the result of the update (failure or success) : the details (exit code, name, etc) about 133 | which app failed to start is given. 134 | 135 | :param dictionnary base: Dictionnary storing information about a Hawkbit update. 136 | """ 137 | 138 | if self.action_id is not None: 139 | self.logger.info('Deployment is already in progress') 140 | return 141 | 142 | # retrieve action id and resource parameter from URL 143 | deployment = base['_links']['deploymentBase']['href'] 144 | match = re.search('/deploymentBase/(.+)\?c=(.+)$', deployment) 145 | action_id, resource = match.groups() 146 | # fetch deployment information 147 | deploy_info = await self.ddi.deploymentBase[action_id](resource) 148 | reboot_needed = False 149 | 150 | chunks_qty = len(deploy_info['deployment']['chunks']) 151 | 152 | if chunks_qty == 0: 153 | msg = 'Deployment without chunks found. Ignoring' 154 | status_execution = DeploymentStatusExecution.closed 155 | status_result = DeploymentStatusResult.failure 156 | await self.ddi.deploymentBase[action_id].feedback( 157 | status_execution, status_result, [msg]) 158 | raise APIError(msg) 159 | else: 160 | msg = "FullMetalUpdate:Proceeding" 161 | percentage = {"cnt": 0, "of": chunks_qty} 162 | status_execution = DeploymentStatusExecution.proceeding 163 | status_result = DeploymentStatusResult.none 164 | await self.ddi.deploymentBase[action_id].feedback( 165 | status_execution, status_result, [msg], 166 | percentage=percentage) 167 | 168 | self.action_id = action_id 169 | 170 | seq = ('name', 'version', 'rev', 'part', 'autostart', 'autoremove', 'status_execution', 'status_update', 'status_result', 'notify', 'timeout') 171 | updates = [] 172 | 173 | # Update process 174 | for chunk in deploy_info['deployment']['chunks']: 175 | update = dict.fromkeys(seq) 176 | # parse the metadata included in the update 177 | for meta in chunk['metadata']: 178 | if meta['key'] == 'rev': 179 | update['rev'] = meta['value'] 180 | if meta['key'] == 'autostart': 181 | update['autostart'] = int(meta['value']) 182 | if meta['key'] == 'autoremove': 183 | update['autoremove'] = int(meta['value']) 184 | if meta['key'] == 'notify': 185 | update['notify'] = int(meta['value']) 186 | if meta['key'] == 'timeout': 187 | update['timeout'] = int(meta['value']) 188 | update['name'] = chunk['name'] 189 | update['version'] = chunk['version'] 190 | update['part'] = chunk['part'] 191 | 192 | self.logger.info("Updating chunk part: {}".format(update['part'])) 193 | 194 | if update['part'] == 'os': 195 | 196 | # checking if we just rebooted and we need to send the feedback in which 197 | # case we don't need to pull the update image again 198 | [feedback, reboot_data] = self.feedback_for_os_deployment(update['rev']) 199 | if feedback: 200 | await self.ddi.deploymentBase[reboot_data['action_id']].feedback( 201 | DeploymentStatusExecution(reboot_data['status_execution']), 202 | DeploymentStatusResult(reboot_data['status_result']), 203 | [reboot_data['msg']]) 204 | self.action_id = None 205 | return 206 | 207 | self.logger.info("OS {} v.{} - updating...".format(update['name'], update['version'])) 208 | update['status_update'] = self.update_system(update['rev']) 209 | update['status_execution'] = DeploymentStatusExecution.closed 210 | if not update['status_update']: 211 | msg = "OS {} v.{} Deployment failed".format(update['name'], update['version']) 212 | self.logger.error(msg) 213 | update['status_result'] = DeploymentStatusResult.failure 214 | await self.ddi.deploymentBase[self.action_id].feedback( 215 | update['status_execution'], update['status_result'], [msg]) 216 | return 217 | else: 218 | msg = "OS {} v.{} Deployment succeed".format(update['name'], update['version']) 219 | self.logger.info(msg) 220 | update['status_result'] = DeploymentStatusResult.success 221 | reboot_needed = True 222 | self.write_reboot_data(self.action_id, 223 | update['status_execution'], 224 | update['status_result'], 225 | msg) 226 | 227 | elif update['part'] == 'bApp': 228 | self.logger.info("App {} v.{} - updating...".format(update['name'], update['version'])) 229 | update['status_update'] = self.update_container(update['name'], update['rev'], update['autostart'], update['autoremove'], update['notify'], update['timeout']) 230 | update['status_execution'] = DeploymentStatusExecution.closed 231 | updates.append(update) 232 | 233 | self.systemd.Reload() 234 | 235 | seq = [update['name'] for update in updates] 236 | self.mutexResults.acquire() 237 | self.feedbackResults = dict.fromkeys(seq) 238 | self.mutexResults.release() 239 | 240 | # Container restart process 241 | for update in updates: 242 | update['status_update'] &= self.handle_container(update['name'], update['autostart'], update['autoremove']) 243 | 244 | final_result = True 245 | fails = "" 246 | feedbackThreadIt = iter(self.feedbackThreads) 247 | 248 | # Hawkbit server feedback process 249 | for update in updates: 250 | if update['notify'] == 1: 251 | next(feedbackThreadIt).join() 252 | self.mutexResults.acquire() 253 | update['status_update'] &= self.feedbackResults[update['name']]['status_update'] 254 | feedbackMsg = self.feedbackResults[update['name']]['msg'] 255 | self.mutexResults.release() 256 | 257 | if not update['status_update']: 258 | msg = "App {} v.{} Deployment failed\n {}".format(update['name'], update['version'], feedbackMsg) 259 | self.logger.error(msg) 260 | update['status_result'] = DeploymentStatusResult.failure 261 | fails += update['name'] + " " 262 | else: 263 | msg = "App {} v.{} Deployment succeed".format(update['name'], update['version']) 264 | self.logger.info(msg) 265 | update['status_result'] = DeploymentStatusResult.success 266 | 267 | final_result &= (update['status_result'] == DeploymentStatusResult.success) 268 | 269 | if(final_result): 270 | msg = "Hawkbit Update Success : All applications have been updated and correctly restarted." 271 | self.logger.info(msg) 272 | status_result = DeploymentStatusResult.success 273 | else: 274 | msg = "Hawkbit Update Failure : " + fails + "failed to update and / or to restart." 275 | self.logger.error(msg) 276 | status_result = DeploymentStatusResult.failure 277 | await self.ddi.deploymentBase[self.action_id].feedback(DeploymentStatusExecution.closed, status_result, [msg]) 278 | 279 | self.action_id = None 280 | if reboot_needed: 281 | try: 282 | subprocess.run("reboot") 283 | except subprocess.CalledProcessError as e: 284 | self.logger.error("Reboot failed: {}".format(e)) 285 | 286 | async def sleep(self, base): 287 | """ 288 | Timeout between two Hawkbit server polling tryouts. This sleep time is suggested by HawkBit. 289 | 290 | :param dictionnary base: Dictionnary storing information about a Hawkbit update. 291 | """ 292 | sleep_str = base['config']['polling']['sleep'] 293 | self.logger.info('Will sleep for {}'.format(sleep_str)) 294 | t = datetime.strptime(sleep_str, '%H:%M:%S') 295 | delta = timedelta(hours=t.hour, minutes=t.minute, seconds=t.second) 296 | await asyncio.sleep(delta.total_seconds()) 297 | 298 | async def poll_base_resource(self): 299 | """ 300 | This method polls the server for new updates and takes action depending on polling results. 301 | 302 | Wrapped in start_polling() to ease exceptions handling, this method continuously runs polling the server. 303 | """ 304 | 305 | while True: 306 | base = await self.ddi() 307 | 308 | if '_links' in base: 309 | if 'configData' in base['_links']: 310 | await self.identify() 311 | if 'deploymentBase' in base['_links']: 312 | await self.process_deployment(base) 313 | if 'cancelAction' in base['_links']: 314 | await self.cancel(base) 315 | 316 | await self.sleep(base) 317 | 318 | def update_container(self, container_name, rev_number, autostart, autoremove, notify=None, timeout=None): 319 | """ 320 | Wrapper method to execute the different steps of a container update. 321 | 322 | :param string container_name: Name of the container. 323 | :param string rev_number: Commit revision. 324 | :param int autostart: set to 1 if the container should be automatically started, 0 otherwise 325 | :param int autoremove: if set to 1, the container's directory will be deleted 326 | :param int action_id: Unique identifier of an Hawkbit update. 327 | :param int notify: Set to 1 if the container is a notify container. 328 | :param int timeout: Timeout value of the communication socket. 329 | """ 330 | try: 331 | self.init_container_remote(container_name) 332 | self.pull_ostree_ref(True, rev_number, container_name) 333 | self.checkout_container(container_name, rev_number) 334 | self.update_container_ids(container_name) 335 | if (autostart == 1) and (notify == 1) and (autoremove != 1): 336 | feedback_thread = self.create_and_start_feedback_thread(container_name, rev_number, autostart, autoremove, timeout) 337 | self.feedbackThreads.append(feedback_thread) 338 | self.create_unit(container_name) 339 | except Exception as e: 340 | self.logger.error("Updating {} failed ({})".format(container_name, e)) 341 | return False 342 | return True 343 | 344 | def update_system(self, rev_number): 345 | """ 346 | Wrapper method to execute the different steps of a OS update. 347 | 348 | :param string rev_number: Commit revision. 349 | """ 350 | try: 351 | self.pull_ostree_ref(False, rev_number) 352 | self.ostree_stage_tree(rev_number) 353 | self.delete_init_var() 354 | except Exception as e: 355 | self.logger.error("Updating the OS failed ({})".format(e)) 356 | return False 357 | return True 358 | 359 | def write_reboot_data(self, action_id, status_execution, status_result, msg): 360 | """ 361 | Write information about the current update in a json file. 362 | 363 | :param int action_id: Unique identifier of an Hawkbit update. 364 | :param DeploymentStatusExecution status_execution: Execution status of the current Hawkbit update. 365 | :param DeploymentStatusResult status_result: Result status of the current Hawkbit update. 366 | :param string msg: Message to be sent to the Hawkbit server. 367 | :raises IOError: Exception raised if writting reboot data into a json file failed. 368 | """ 369 | # the enums are not serializable thus we store their value 370 | reboot_data = { 371 | "action_id": action_id, 372 | "status_execution": status_execution.value, 373 | "status_result": status_result.value, 374 | "msg": msg 375 | } 376 | 377 | try: 378 | with open(PATH_REBOOT_DATA, "w") as f: 379 | json.dump(reboot_data, f) 380 | except IOError as e: 381 | self.logger.error("Writing reboot data failed ({})".format(e)) 382 | 383 | def feedback_for_os_deployment(self, revision): 384 | """ 385 | This method will generate a feedback message for the Hawkbit server and 386 | return the reboot data which will be used by the the DDI client to return 387 | the appropriate feedback message. 388 | 389 | :param checksum revision: Checksum of revision stored on OSTree remote repository. 390 | :returns: (True, reboot_data) if the reboot data json file has been correctly found and updated. 391 | :raises FileNotFoundError: Exception raised if the reboot data json file has not been found. 392 | """ 393 | 394 | reboot_data = None 395 | try: 396 | with open(PATH_REBOOT_DATA, "r") as f: 397 | reboot_data = json.load(f) # json.load() return a JSON object (similar to a dictionnary whose keys are strings and whose values are JSON types) 398 | if reboot_data is None: 399 | self.logger.error("Rebooting data loading failed") 400 | except FileNotFoundError: 401 | return (False, None) 402 | 403 | if self.check_for_rollback(revision): 404 | reboot_data.update({"status_result": DeploymentStatusResult.failure.value}) 405 | reboot_data.update({"msg": "Deployment has failed and system has rollbacked"}) 406 | 407 | os.remove(PATH_REBOOT_DATA) 408 | 409 | return (True, reboot_data) 410 | 411 | def create_and_start_feedback_thread(self, container_name, rev, autostart, autoremove, timeout): 412 | """ 413 | This method is called to initialize and start the feedback thread used to 414 | feedback the server the status of a container whose notify variable is set. See the 415 | container_feedbacker thread method. 416 | 417 | :param string container_name: Name of the container. 418 | :param string rev: Commit revision, used for rollbacking. 419 | :param int autostart: Autostart variable of the container, used for rollbacking. 420 | :param int autoremove: Autoremove of the container, used for rollbacking. 421 | :param int timeout: Timeout value of the communication socket. 422 | """ 423 | sock_name = "fullmetalupdate_notify_" + container_name + ".sock" 424 | self.logger.info("Creating socket {}".format(sock_name)) 425 | sock = s.socket(s.AF_UNIX, s.SOCK_STREAM) 426 | sock.settimeout(timeout) 427 | if os.path.exists(DIR_NOTIFY_SOCKET + sock_name): 428 | os.remove(DIR_NOTIFY_SOCKET + sock_name) 429 | sock.bind(DIR_NOTIFY_SOCKET + sock_name) 430 | 431 | container_feedbackd = Thread( 432 | target=self.container_feedbacker, 433 | args=(sock, 434 | container_name, 435 | rev, 436 | autostart, 437 | autoremove), 438 | name= "container-feedback-" + container_name) 439 | container_feedbackd.start() 440 | return container_feedbackd 441 | 442 | def container_feedbacker(self, 443 | socket, 444 | container_name, 445 | rev_number, 446 | autostart, 447 | autoremove): 448 | """ 449 | This thread method is used to feedback the server for containers which provide 450 | the notify feature of systemd. It will trigger a rollback on the container in case 451 | of failure (if possible). 452 | 453 | This method will wait on an Unix socket for information about the notify result, 454 | and proceed in consequence. 455 | 456 | :param socket socket: Socket used for communication between the container service and this thread. 457 | :param string container_name: Name of the container. 458 | :param string rev: Commit revision, used for rollbacking. 459 | :param int autostart: Autostart variable of the container, used for rollbacking. 460 | :param int autoremove: Autoremove of the container, used for rollbacking. 461 | """ 462 | 463 | try: 464 | sock_name = "fullmetalupdate_notify_" + container_name + ".sock" 465 | socket.listen(1) 466 | [conn, _] = socket.accept() 467 | datagram = conn.recv(1024) 468 | 469 | if datagram: 470 | systemd_info = datagram.strip().decode("utf-8").split() 471 | self.logger.debug("Datagram received : {}".format(systemd_info)) 472 | 473 | if systemd_info[0] == 'success': 474 | # feedback the server positively 475 | msg = "Container " + container_name + " started successfully" 476 | status_update = True 477 | self.logger.info(msg) 478 | # Write this new revision for future updates 479 | self.set_current_revision(container_name, rev_number) 480 | else: 481 | # rollback + feedback the server negatively 482 | status_update = False 483 | end_msg = self.rollback_container(container_name, autostart, autoremove) 484 | msg = "Container " + container_name + " failed to start with result :" \ 485 | + "\n\tSERVICE_RESULT=" + systemd_info[0] \ 486 | + "\n\tEXIT_CODE=" + systemd_info[1] \ 487 | + "\n\tEXIT_STATUS=" + systemd_info[2] \ 488 | + end_msg 489 | self.logger.info(msg) 490 | except s.timeout: 491 | # socket timeout, try to rollback if possible 492 | status_update = False 493 | msg = "Container " + container_name + " failed to start : the socket timed out." 494 | self.logger.error(msg) 495 | end_msg = self.rollback_container(container_name, 496 | autostart, 497 | autoremove) 498 | msg += end_msg 499 | 500 | socket.close() 501 | self.logger.info("Removing socket {}".format(sock_name)) 502 | try: 503 | os.remove(DIR_NOTIFY_SOCKET + sock_name) 504 | except FileNotFoundError as e: 505 | self.logger.error("Error while removing socket ({})".format(e)) 506 | 507 | self.mutexResults.acquire() 508 | self.feedbackResults[container_name] = dict.fromkeys(("status_update", "msg")) 509 | self.feedbackResults[container_name]["status_update"] = status_update 510 | self.feedbackResults[container_name]["msg"] = msg 511 | self.mutexResults.release() 512 | 513 | def rollback_container(self, container_name, autostart, autoremove): 514 | """ 515 | This method Rollbacks the container, if possible, and returns a message that will 516 | be sent to the server. 517 | 518 | :param string container_name: Name of the container. 519 | :param int autostart: Autostart variable of the container, used for rollbacking. 520 | :param int autoremove: Autoremove of the container, used for rollbacking. 521 | 522 | :returns: End of the message that will be sent, which depends on the status of the rollback (performed or not) 523 | :rtype: string 524 | """ 525 | 526 | end_msg = "" 527 | previous_rev = self.get_previous_rev(container_name) 528 | 529 | if previous_rev is None: 530 | end_msg = "\nFirst installation of the container, cannot rollback." 531 | else: 532 | res = self.update_container(container_name, previous_rev, autostart, autoremove) 533 | self.systemd.Reload() 534 | res &= self.handle_container(container_name, autostart, autoremove) 535 | if res: 536 | end_msg = "\nContainer has rollbacked." 537 | else: 538 | end_msg = "\nContainer has failed to rollback." 539 | 540 | return end_msg 541 | -------------------------------------------------------------------------------- /fullmetalupdate/updater.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import logging 4 | import os 5 | import shutil 6 | import subprocess 7 | import json 8 | import gi 9 | 10 | gi.require_version("OSTree", "1.0") 11 | from gi.repository import OSTree, GLib, Gio 12 | from pydbus import SystemBus 13 | 14 | PATH_APPS = '/apps' 15 | PATH_REPO_OS = '/ostree/repo/' 16 | PATH_REPO_APPS = PATH_APPS + '/ostree_repo' 17 | PATH_SYSTEMD_UNITS = '/etc/systemd/system/' 18 | PATH_CURRENT_REVISIONS = '/var/local/fullmetalupdate/current_revs.json' 19 | VALIDATE_CHECKOUT = 'CheckoutDone' 20 | FILE_AUTOSTART = 'auto.start' 21 | CONTAINER_UID = 1000 22 | CONTAINER_GID = 1000 23 | OSTREE_DEPTH = 1 24 | 25 | class DBUSException(Exception): 26 | pass 27 | 28 | 29 | class AsyncUpdater(object): 30 | """ FullMetalUpdate client updater library. 31 | 32 | Provides methods to perform all different step of a FMU update. 33 | 34 | :param logging logger: Logger used to print information regarding the update proceedings or to report errors. 35 | :param pydbus.SystemBus systemd: Allow to use systemd services exposed over D-Bus. 36 | :param OSTree.Sysroot sysroot: Python instance of rootfs (root file system) of the system. 37 | :param OSTree.Repo repo_containers: Python instance of the OSTree remote repository for containers. 38 | :param OSTree.Repo repo_os: Python instance of the OSTree remote repository for the OS. 39 | """ 40 | 41 | def __init__(self): 42 | """ Constructor of AsyncUpdater Class. 43 | """ 44 | 45 | self.ostree_remote_attributes = None 46 | 47 | self.logger = logging.getLogger('fullmetalupdate_container_updater') 48 | 49 | self.mark_os_successful() 50 | 51 | bus = SystemBus() 52 | self.systemd = bus.get('.systemd1') 53 | 54 | self.sysroot = OSTree.Sysroot.new_default() 55 | self.sysroot.load(None) 56 | self.logger.info("Cleaning the sysroot") 57 | self.sysroot.cleanup(None) 58 | 59 | [_, repo] = self.sysroot.get_repo() 60 | self.repo_os = repo 61 | 62 | self.remote_name_os = None 63 | self.repo_containers = OSTree.Repo.new(Gio.File.new_for_path(PATH_REPO_APPS)) 64 | if os.path.exists(PATH_REPO_APPS): 65 | self.logger.info("Preinstalled OSTree for containers, we use it") 66 | self.repo_containers.open(None) 67 | else: 68 | self.logger.info("No preinstalled OSTree for containers, we create one") 69 | self.repo_containers.create(OSTree.RepoMode.BARE_USER_ONLY, None) 70 | 71 | def mark_os_successful(self): 72 | """ This method marks the currently running OS as successful by setting the init_var u-boot environment variable to 1. 73 | 74 | :returns: - True if the variable was successfully set 75 | - False otherwise 76 | :raises subprocess.CalledProcessError: Exception raised if u-boot environment variable failed to be set up to 1. 77 | """ 78 | try: 79 | if subprocess.call(["fw_setenv", "success", "1"]) == 0: 80 | self.logger.info("Setting success u-boot environment variable to 1 succeeded") 81 | else: 82 | self.logger.error("Setting success u-boot environment variable to 1 failed") 83 | 84 | except subprocess.CalledProcessError as e: 85 | self.logger.error("Ostree rollback post-process commands failed ({})".format(str(e))) 86 | 87 | def check_for_rollback(self, revision): 88 | """ 89 | Function used to execute the different commands needed for the rollback to be effective. 90 | 91 | We check : 92 | - if the booted deployment's revision matches the server's revision 93 | - if so, check if there is a pending deployment (meaning we've rollbacked) and 94 | undeploy it. 95 | 96 | :param checksum revision: Checksum of revision stored on OSTree remote repository. 97 | :returns: - True when the system has rollbacked 98 | - False otherwise 99 | :raises subprocess.CalledProcessError: Exception raised if rollback post-processing fails. 100 | """ 101 | try: 102 | has_rollbacked = False 103 | 104 | # returns [pendings deployments, rollback deployments] 105 | deployments = self.sysroot.query_deployments_for(None) 106 | 107 | # the deployment we are booted on 108 | booted_deployment_rev = self.sysroot.get_booted_deployment().get_csum() 109 | 110 | if booted_deployment_rev != revision: 111 | has_rollbacked = True 112 | self.logger.warning("The system rollbacked. Checking if we needed to undeploy") 113 | if deployments[0] is not None: 114 | self.logger.info("There is a pending deployment. Undeploying...") 115 | # 0 is the index of the pending deployment (if there is one) 116 | if subprocess.call(["ostree", "admin", "undeploy", "0"]) != 0: 117 | self.logger.error("Undeployment failed") 118 | else: 119 | self.logger.info("Undeployment successful") 120 | else: 121 | self.logger.info("No undeployment needed") 122 | 123 | return has_rollbacked 124 | 125 | except subprocess.CalledProcessError as e: 126 | self.logger.error("Ostree rollback post-process commands failed ({})".format(str(e))) 127 | return False 128 | 129 | def init_ostree_remotes(self, ostree_remote_attributes): 130 | """ 131 | This method initializes the OSTree remote repositories (both OS repo and containers repo). 132 | 133 | :param dictionnary ostree_remote_attributes: Dictionnary containing the name, the url and whether the images are signed with GPG or not. 134 | :returns: - True if the initialization is successful 135 | - False otherwise 136 | :raises GLib.Error: Exception raised if OSTree remote repositories initialization fails. 137 | """ 138 | res = True 139 | self.ostree_remote_attributes = ostree_remote_attributes 140 | opts = GLib.Variant('a{sv}', {'gpg-verify': GLib.Variant('b', ostree_remote_attributes['gpg-verify'])}) 141 | try: 142 | self.logger.info("Initalize remotes for the OS ostree: {}".format(ostree_remote_attributes['name'])) 143 | if not ostree_remote_attributes['name'] in self.repo_os.remote_list(): 144 | self.repo_os.remote_add(ostree_remote_attributes['name'], 145 | ostree_remote_attributes['url'], 146 | opts, None) 147 | self.remote_name_os = ostree_remote_attributes['name'] 148 | 149 | [_, refs] = self.repo_containers.list_refs(None, None) 150 | 151 | self.logger.info("Initalize remotes for the containers ostree: {}".format(refs)) 152 | for ref in refs: 153 | remote_name = ref.split(':')[0] 154 | if remote_name not in self.repo_containers.remote_list(): 155 | self.logger.info("We had the remote: {}".format(remote_name)) 156 | self.repo_containers.remote_add(remote_name, 157 | ostree_remote_attributes['url'], 158 | opts, None) 159 | 160 | except GLib.Error as e: 161 | self.logger.error("OSTRee remote initialization failed ({})".format(str(e))) 162 | res = False 163 | 164 | return res 165 | 166 | def set_current_revision(self, container_name, rev): 167 | """ 168 | This method writes rev into a json file containing the current working rev for the containers. 169 | 170 | :param string container_name: Name of the container. 171 | :param string rev: Revision to write in json file. 172 | :raises FileNotFoundError: Exception raised if json file needs to be created. 173 | """ 174 | try: 175 | with open(PATH_CURRENT_REVISIONS, "r") as f: 176 | current_revs = json.load(f) 177 | current_revs.update({container_name: rev}) 178 | with open(PATH_CURRENT_REVISIONS, "w") as f: 179 | json.dump(current_revs, f, indent=4) 180 | except FileNotFoundError: 181 | with open(PATH_CURRENT_REVISIONS, "w") as f: 182 | current_revs = {container_name: rev} 183 | json.dump(current_revs, f, indent=4) 184 | 185 | def get_previous_rev(self, container_name): 186 | """ 187 | This method returns the previous working revision of a notify container. 188 | 189 | :param string container_name: Name of the container. 190 | :returns: - The rev sha for container_name 191 | - None if the container isn't found 192 | :raises KeyError: Execution raised if container associated with container_name doesn't exist. 193 | :raises FileNotFoundError: Execution raised if no file with previous rev exists. 194 | """ 195 | try: 196 | with open(PATH_CURRENT_REVISIONS, "r") as f: 197 | current_revs = json.load(f) 198 | return current_revs[container_name] 199 | except (FileNotFoundError, KeyError): 200 | return None 201 | 202 | def init_checkout_existing_containers(self): 203 | """ 204 | This method manages: 205 | - it checks out the containers installed on the target ; 206 | - then it copies the service files from /apps partition to the right location ; 207 | - then it regenerates systemd dependancy tree ; 208 | - last but not least, it starts the containers. 209 | 210 | :returns: - True if the containers are successfully initialized 211 | - False otherwise 212 | """ 213 | res = True 214 | self.logger.info("Getting refs from repo:{}".format(PATH_REPO_APPS)) 215 | 216 | try: 217 | [_, refs] = self.repo_containers.list_refs(None, None) 218 | self.logger.info("There are {} containers to be started.".format(len(refs))) 219 | for ref in refs: 220 | container_name = ref.split(':')[1] 221 | if not os.path.isfile(PATH_APPS + '/' + container_name + '/' + VALIDATE_CHECKOUT): 222 | self.checkout_container(container_name, None) 223 | self.update_container_ids(container_name) 224 | if not res: 225 | self.logger.error("Error when checking out container:{}".format(container_name)) 226 | break 227 | self.create_unit(container_name) 228 | self.systemd.Reload() 229 | for ref in refs: 230 | container_name = ref.split(':')[1] 231 | if os.path.isfile(PATH_APPS + '/' + container_name + '/' + FILE_AUTOSTART): 232 | self.start_unit(container_name) 233 | except (GLib.Error, Exception) as e: 234 | self.logger.error("Error checking out containers repo ({})".format(e)) 235 | res = False 236 | finally: 237 | return res 238 | 239 | def create_unit(self, container_name): 240 | """ 241 | This method copies the .service file from /apps partition to /etc/systemd/system/ in order to create the unit for the relevant container. 242 | 243 | :param string container_name: Name of the container. 244 | """ 245 | self.logger.info("Copy the service file to /etc/systemd/system/{}.service".format(container_name)) 246 | shutil.copy(PATH_APPS + '/' + container_name + '/systemd.service', 247 | PATH_SYSTEMD_UNITS + container_name + '.service') 248 | 249 | def start_unit(self, container_name): 250 | """ 251 | This method enables and then starts the systemd unit for the relevant container. 252 | 253 | :param string container_name: Name of the container. 254 | """ 255 | self.logger.info("Enable the container {}".format(container_name)) 256 | self.systemd.EnableUnitFiles([container_name + '.service'], False, False) 257 | self.logger.info("Since FILE_AUTOSTART is present, start the container using systemd") 258 | self.systemd.StartUnit(container_name + '.service', "replace") 259 | 260 | def stop_unit(self, container_name): 261 | """ 262 | This method stops the systemd unit for the relevant container. 263 | 264 | :param string container_name: Name of the container. 265 | """ 266 | self.logger.info("Since FILE_AUTOSTART is not present, stop the container using systemd") 267 | self.systemd.StopUnit(container_name + '.service', "replace") 268 | self.logger.info("Disable the container {}".format(container_name)) 269 | self.systemd.DisableUnitFiles([container_name + '.service'], False) 270 | 271 | def pull_ostree_ref(self, is_container, ref_sha, ref_name=None): 272 | """ 273 | Wrapper method to pull a ref from an OSTree remote repository. 274 | 275 | :param boolean is_container: - True to pull a container image 276 | - False to pull an OS image 277 | :param string ref_sha: SHA checksum of the ref commit to pull. 278 | :param string ref_name: Name of the ref commit to pull (can be the name of the container, if None, the OS name will be set). 279 | """ 280 | res = True 281 | 282 | if is_container: 283 | repo = self.repo_containers 284 | else: 285 | repo = self.repo_os 286 | ref_name = self.remote_name_os 287 | 288 | try: 289 | progress = OSTree.AsyncProgress.new() 290 | progress.connect('changed', OSTree.Repo.pull_default_console_progress_changed, None) 291 | 292 | opts = GLib.Variant('a{sv}', {'flags': GLib.Variant('i', OSTree.RepoPullFlags.NONE), 293 | 'refs': GLib.Variant('as', (ref_sha,)), 294 | 'depth': GLib.Variant('i', OSTREE_DEPTH)}) 295 | self.logger.info("Pulling remote {} from OSTree repo ({})".format(ref_name, ref_sha)) 296 | res = repo.pull_with_options(ref_name, opts, progress, None) 297 | progress.finish() 298 | self.logger.info("Upgrader pulled {} from OSTree repo ({})".format(ref_name, ref_sha)) 299 | except GLib.Error as e: 300 | self.logger.error("Pulling {} from OSTree repo failed ({})".format(ref_name, str(e))) 301 | raise 302 | if not res: 303 | raise Exception("Pulling {} failed (returned False)".format(ref_name)) 304 | 305 | def init_container_remote(self, container_name): 306 | """ 307 | If the container does not exist, initialize its remote. 308 | 309 | :param string container_name: Name of the container. 310 | """ 311 | 312 | # returns [('container-hello-world.service', 'description', 'loaded', 'failed', 'failed', '', '/org/freedesktop/systemd1/unit/wtk_2dnodejs_2ddemo_2eservice', 0, '', '/')] 313 | service = self.systemd.ListUnitsByNames([container_name + '.service']) 314 | 315 | try: 316 | if (service[0][2] == 'not-found'): 317 | # New service added, we need to connect to its remote 318 | opts = GLib.Variant('a{sv}', 319 | {'gpg-verify': GLib.Variant('b', self.ostree_remote_attributes['gpg-verify'])}) 320 | # Check if this container was not installed previously 321 | if container_name not in self.repo_containers.remote_list(): 322 | self.logger.info("New container added to the target, " 323 | "we install the remote: {}".format(container_name)) 324 | self.repo_containers.remote_add(container_name, 325 | self.ostree_remote_attributes['url'], 326 | opts, None) 327 | else: 328 | self.logger.info("New container {} added to the target but the remote " 329 | "already exists, we do nothing".format(container_name)) 330 | except GLib.Error as e: 331 | self.logger.error("Initializing {} remote failed ({})".format(container_name, str(e))) 332 | raise 333 | 334 | def update_container_ids(self, container_name): 335 | """ 336 | By default, the container are checked out as root. This method sets the uid and 337 | gid of all the container related files to 1000 (UID) and 1000 (GID). 338 | 339 | :param string container_name: Name of the container. 340 | """ 341 | self.logger.info("Update the UID and GID of the rootfs") 342 | os.chown(PATH_APPS + '/' + container_name, CONTAINER_UID, CONTAINER_GID) 343 | for dirpath, dirnames, filenames in os.walk(PATH_APPS + '/' + container_name): 344 | for dname in dirnames: 345 | os.lchown(os.path.join(dirpath, dname), CONTAINER_UID, CONTAINER_GID) 346 | for fname in filenames: 347 | os.lchown(os.path.join(dirpath, fname), CONTAINER_UID, CONTAINER_GID) 348 | 349 | def handle_container(self, container_name, autostart, autoremove): 350 | """ 351 | This method will handle the container execution or deletion based on the autostart 352 | and autoremove arguments. 353 | 354 | :param string container_name: Name of the container. 355 | :param int autostart: set to 1 if the container should be automatically started, 0 otherwise 356 | :param int autoremove: if set to 1, the container's directory will be deleted 357 | :returns: - True if the relevant container started correctly 358 | - False otherwise 359 | """ 360 | try: 361 | if autoremove == 1: 362 | self.logger.info("Remove the directory: {}".format(PATH_APPS + '/' + container_name)) 363 | shutil.rmtree(PATH_APPS + '/' + container_name) 364 | else: 365 | service = self.systemd.ListUnitsByNames([container_name + '.service']) 366 | if service[0][2] == 'not-found': 367 | self.logger.info("First installation of the container {} on the " 368 | "system, we create and start the service".format(container_name)) 369 | if os.path.isfile(PATH_APPS + '/' + container_name + '/' + FILE_AUTOSTART): 370 | self.start_unit(container_name) 371 | else: 372 | if autostart == 1: 373 | if not os.path.isfile(PATH_APPS + '/' + container_name + '/' + FILE_AUTOSTART): 374 | open(PATH_APPS + '/' + container_name + '/' + FILE_AUTOSTART, 'a').close() 375 | self.start_unit(container_name) 376 | else: 377 | if os.path.isfile(PATH_APPS + '/' + container_name + '/' + FILE_AUTOSTART): 378 | os.remove(PATH_APPS + '/' + container_name + '/' + FILE_AUTOSTART) 379 | except Exception as e: 380 | self.logger.error("UpdateTest :: Handling {} failed ({})".format(container_name, e)) 381 | return False 382 | return True 383 | 384 | def checkout_container(self, container_name, rev_number): 385 | """ 386 | This method checks out a container into its corresponding folder, to a given commit revision. 387 | Before that, it stops the container using systemd, if found. 388 | 389 | :param string container_name: Name of the container. 390 | :param string rev_number: Commit revision. 391 | """ 392 | service = self.systemd.ListUnitsByNames([container_name + '.service']) 393 | if service[0][2] != 'not-found': 394 | self.logger.info("Stop the container {}".format(container_name)) 395 | self.stop_unit(container_name) 396 | 397 | res = True 398 | rootfs_fd = None 399 | try: 400 | options = OSTree.RepoCheckoutAtOptions() 401 | options.overwrite_mode = OSTree.RepoCheckoutOverwriteMode.UNION_IDENTICAL 402 | options.process_whiteouts = True 403 | options.bareuseronly_dirs = True 404 | options.no_copy_fallback = True 405 | options.mode = OSTree.RepoCheckoutMode.USER 406 | 407 | self.logger.info("Getting rev from repo:{}".format(container_name + ':' + container_name)) 408 | 409 | if rev_number is None: 410 | rev = self.repo_containers.resolve_rev(container_name + ':' + container_name, False)[1] 411 | else: 412 | rev = rev_number 413 | self.logger.info("Rev value:{}".format(rev)) 414 | if os.path.isdir(PATH_APPS + '/' + container_name): 415 | shutil.rmtree(PATH_APPS + '/' + container_name) 416 | os.mkdir(PATH_APPS + '/' + container_name) 417 | self.logger.info("Create directory {}/{}".format(PATH_APPS, container_name)) 418 | rootfs_fd = os.open(PATH_APPS + '/' + container_name, os.O_DIRECTORY) 419 | res = self.repo_containers.checkout_at(options, rootfs_fd, PATH_APPS + '/' + container_name, rev) 420 | open(PATH_APPS + '/' + container_name + '/' + VALIDATE_CHECKOUT, 'a').close() 421 | 422 | except GLib.Error as e: 423 | self.logger.error("Checking out {} failed ({})".format(container_name, str(e))) 424 | raise 425 | if rootfs_fd is not None: 426 | os.close(rootfs_fd) 427 | if not res: 428 | raise Exception("Checking out {} failed (returned False)") 429 | 430 | def ostree_stage_tree(self, rev_number): 431 | """ 432 | Wrapper around sysroot.stage_tree() 433 | 434 | Deploy new revision, however finalization only occurs at shutdown time. 435 | 436 | :param string rev_number: Commit revision. 437 | """ 438 | try: 439 | booted_dep = self.sysroot.get_booted_deployment() 440 | if booted_dep is None: 441 | raise Exception("Not booted in an OSTree system") 442 | [_, checksum] = self.repo_os.resolve_rev(rev_number, False) 443 | origin = booted_dep.get_origin() 444 | osname = booted_dep.get_osname() 445 | 446 | [res, _] = self.sysroot.stage_tree(osname, checksum, origin, booted_dep, None, None) 447 | 448 | self.logger.info("Staged the new OS tree. The new deployment will be ready after a reboot") 449 | 450 | except GLib.Error as e: 451 | self.logger.error("Failed while staging new OS tree ({})".format(e)) 452 | raise 453 | if not res: 454 | raise Exception("Failed while staging new OS tree (returned False)") 455 | 456 | def delete_init_var(self): 457 | """ 458 | This method delete u-boot's environment variable init_var, to restart the rollback procedure. 459 | """ 460 | try: 461 | self.logger.info("Deleting init_var u-boot environment variable") 462 | if subprocess.call(["fw_setenv", "init_var"]) != 0: 463 | self.logger.error("Deleting init_var variable from u-boot environment failed") 464 | else: 465 | self.logger.info("Deleting init_var variable from u-boot environment succeeded") 466 | except subprocess.CalledProcessError as e: 467 | self.logger.error("Deleting init_var variable from u-boot environment failed ({})".format(e)) 468 | raise 469 | -------------------------------------------------------------------------------- /rauc_hawkbit/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FullMetalUpdate/fullmetalupdate/8135496159cc6f2b7c1cd87f6b92a0f23e22b591/rauc_hawkbit/__init__.py -------------------------------------------------------------------------------- /rauc_hawkbit/config.cfg: -------------------------------------------------------------------------------- 1 | [client] 2 | hawkbit_server = 127.0.0.1 3 | ssl = false 4 | tenant_id = DEFAULT 5 | target_name = test-target 6 | auth_token = ahVahL1Il1shie2aj2poojeChee6ahShu 7 | mac_address = ff:ff:ff:ff:ff:ff 8 | bundle_download_location = /tmp/bundle.raucb 9 | log_level = debug 10 | -------------------------------------------------------------------------------- /rauc_hawkbit/dbus_client.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import asyncio 4 | from gi.repository import Gio 5 | import logging 6 | import traceback 7 | 8 | 9 | class DBUSException(Exception): 10 | pass 11 | 12 | 13 | class AsyncDBUSClient(object): 14 | def __init__(self): 15 | self.logger = logging.getLogger('rauc_hawkbit') 16 | self.dbus_events = asyncio.Queue() 17 | loop = asyncio.get_event_loop() 18 | # handle dbus events in async way 19 | self.dbus_event_task = loop.create_task(self.handle_dbus_event()) 20 | # holds active subscriptions 21 | self.signal_subscriptions = [] 22 | # ({interface}, {signal}): {callback} 23 | self.signal_callbacks = {} 24 | # ({interface}, {property}): {callback} 25 | self.property_callbacks = {} 26 | 27 | self.system_bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None) 28 | 29 | # always subscribe to property changes by default 30 | self.new_signal_subscription('org.freedesktop.DBus.Properties', 31 | 'PropertiesChanged', 32 | self.property_changed_callback) 33 | 34 | def __del__(self): 35 | self.cleanup_dbus() 36 | 37 | def cleanup_dbus(self): 38 | """Unsubscribe on deletion.""" 39 | for subscription in self.signal_subscriptions: 40 | self.system_bus.signal_unsubscribe(subscription) 41 | 42 | self.dbus_event_task.cancel() 43 | 44 | def on_dbus_event(self, *args): 45 | """Generic sync callback for all DBUS events.""" 46 | self.dbus_events.put_nowait(args) 47 | 48 | async def handle_dbus_event(self): 49 | """ 50 | Retrieves DBUS events from queue and calls corresponding async 51 | callback. 52 | """ 53 | while True: 54 | try: 55 | event = await self.dbus_events.get() 56 | interface = event[3] 57 | signal = event[4] 58 | await self.signal_callbacks[(interface, signal)](*event) 59 | except Exception as e: 60 | traceback.print_exc() 61 | self.logger.error(str(e)) 62 | 63 | def new_proxy(self, interface, object_path): 64 | """Returns a new managed proxy.""" 65 | # assume name is interface without last part 66 | name = '.'.join(interface.split('.')[:-1]) 67 | proxy = Gio.DBusProxy.new_sync(self.system_bus, 0, None, name, 68 | object_path, interface, None) 69 | 70 | # FIXME: check for methods 71 | if len(proxy.get_cached_property_names()) == 0: 72 | self.logger.warning('Proxy {} contains no properties') 73 | 74 | return proxy 75 | 76 | def new_signal_subscription(self, interface, signal, callback): 77 | """Add new signal subscription.""" 78 | signal_subscription = self.system_bus.signal_subscribe( 79 | None, interface, signal, None, None, 0, self.on_dbus_event) 80 | self.signal_callbacks[(interface, signal)] = callback 81 | self.signal_subscriptions.append(signal_subscription) 82 | 83 | def new_property_subscription(self, interface, property_, callback): 84 | """Add new property subscription.""" 85 | self.property_callbacks[(interface, property_)] = callback 86 | 87 | async def property_changed_callback(self, connection, sender_name, 88 | object_path, interface_name, 89 | signal_name, parameters): 90 | """ 91 | Callback for changed properties. Calls callbacks for changed 92 | properties as if they were signals. 93 | """ 94 | property_interface = parameters[0] 95 | 96 | changed_properties = {k: v for k, v in parameters[1].items() 97 | if (property_interface, k) in 98 | self.property_callbacks} 99 | 100 | for attribute, status in changed_properties.items(): 101 | await self.property_callbacks[(property_interface, attribute)]( 102 | connection, sender_name, object_path, property_interface, 103 | attribute, status) 104 | -------------------------------------------------------------------------------- /rauc_hawkbit/ddi/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FullMetalUpdate/fullmetalupdate/8135496159cc6f2b7c1cd87f6b92a0f23e22b591/rauc_hawkbit/ddi/__init__.py -------------------------------------------------------------------------------- /rauc_hawkbit/ddi/cancel_action.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from datetime import datetime 4 | from enum import Enum 5 | 6 | 7 | # status of the action execution 8 | CancelStatusExecution = Enum('CancelStatusExecution', 9 | 'closed proceeding canceled scheduled rejected \ 10 | resumed') 11 | 12 | # defined status of the result 13 | CancelStatusResult = Enum('CancelStatusResultFinished', 14 | 'success failure none') 15 | 16 | 17 | class Action(object): 18 | """ 19 | Represents /{tenant}/controller/v1/{targetid}/cancelAction/{actionId} in 20 | HawkBit's DDI API. 21 | """ 22 | def __init__(self, ddi, action_id): 23 | self.ddi = ddi 24 | self.action_id = action_id 25 | 26 | async def __call__(self): 27 | """ 28 | See http://sp.apps.bosch-iot-cloud.com/documentation/rest-api/rootcontroller-api-guide.html#_get_tenant_controller_v1_targetid_cancelaction_actionid # noqa 29 | """ 30 | return await self.ddi.get_resource( 31 | '/{tenant}/controller/v1/{controllerId}/cancelAction/{actionId}', actionId=self.action_id) 32 | 33 | async def feedback(self, status_execution, status_result, 34 | status_details=()): 35 | """ 36 | See http://sp.apps.bosch-iot-cloud.com/documentation/rest-api/rootcontroller-api-guide.html#_post_tenant_controller_v1_targetid_cancelaction_actionid_feedback # noqa 37 | """ 38 | assert isinstance(status_execution, CancelStatusExecution), \ 39 | 'status_execution must be CancelStatusExecution' 40 | assert isinstance(status_result, CancelStatusResult), \ 41 | 'status_result must be CancelStatusResult enum' 42 | assert isinstance(status_details, (tuple, list)), \ 43 | 'status_details must be tuple or list' 44 | 45 | time = datetime.now().strftime('%Y%m%dT%H%M%S') 46 | 47 | post_data = { 48 | 'id': self.action_id, 49 | 'time': time, 50 | 'status': { 51 | 'result': { 52 | 'finished': status_result.name 53 | }, 54 | 'execution': status_execution.name, 55 | 'details': status_details 56 | } 57 | } 58 | 59 | return await self.ddi.post_resource( 60 | '/{tenant}/controller/v1/{controllerId}/cancelAction/{actionId}/feedback', post_data, actionId=self.action_id) 61 | 62 | 63 | class CancelAction(object): 64 | """ 65 | Represents /{tenant}/controller/v1/{targetid}/cancelAction in HawkBit's DDI 66 | API. 67 | """ 68 | def __init__(self, ddi): 69 | self.ddi = ddi 70 | 71 | def __getitem__(self, key): 72 | action_id = key 73 | return Action(self.ddi, action_id) 74 | -------------------------------------------------------------------------------- /rauc_hawkbit/ddi/client.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import aiohttp 4 | import aiohttp.web 5 | import async_timeout 6 | import json 7 | import hashlib 8 | import logging 9 | 10 | from datetime import datetime 11 | from enum import Enum 12 | 13 | from .deployment_base import DeploymentBase 14 | from .softwaremodules import SoftwareModules 15 | from .cancel_action import CancelAction 16 | 17 | # status of the action execution 18 | ConfigStatusExecution = Enum('ConfigStatusExecution', 19 | 'closed proceeding canceled scheduled rejected \ 20 | resumed') 21 | 22 | # defined status of the result 23 | ConfigStatusResult = Enum('ConfigStatusResultFinished', 24 | 'success failure none') 25 | 26 | 27 | class APIError(Exception): 28 | pass 29 | 30 | 31 | class DDIClient(object): 32 | """ 33 | Base Direct Device Integration API client providing GET, POST and PUT 34 | helpers as well as access to next level API resources. 35 | """ 36 | 37 | error_responses = { 38 | 400: 'Bad Request - e.g. invalid parameters', 39 | 401: 'The request requires user authentication.', 40 | 403: 'Insufficient permissions or data volume restriction applies.', 41 | 404: 'Resource not available or device unknown.', 42 | 405: 'Method Not Allowed', 43 | 406: 'Accept header is specified and is not application/json.', 44 | 429: 'Too many requests.' 45 | } 46 | 47 | def __init__(self, session, host, ssl, auth_token, tenant_id, controller_id, timeout=10): 48 | self.session = session 49 | self.host = host 50 | self.ssl = ssl 51 | self.logger = logging.getLogger('rauc_hawkbit') 52 | self.headers = {'Authorization': 'TargetToken {}'.format(auth_token)} 53 | self.tenant = tenant_id 54 | self.controller_id = controller_id 55 | self.timeout = timeout 56 | # URL parts which get replaced lateron 57 | self.placeholders = ['tenant', 'target', 'softwaremodule', 'action', 58 | 'filename'] 59 | self.replacements = { 60 | '/MD5SUM': '.MD5SUM' 61 | } 62 | 63 | @property 64 | def cancelAction(self): 65 | return CancelAction(self) 66 | 67 | @property 68 | def softwaremodules(self): 69 | return SoftwareModules(self) 70 | 71 | @property 72 | def deploymentBase(self): 73 | return DeploymentBase(self) 74 | 75 | async def __call__(self): 76 | """ 77 | Base poll resource 78 | 79 | See https://docs.bosch-iot-rollouts.com/documentation/rest-api/rootcontroller-api-guide.html#_controller_base_poll_resource 80 | 81 | Returns: JSON data 82 | """ 83 | return await self.get_resource('/{tenant}/controller/v1/{controllerId}') 84 | 85 | async def configData(self, status_execution, status_result, action_id='', 86 | status_details=(), **kwdata): 87 | """ 88 | Provide meta informtion during device registration at the update 89 | server. 90 | 91 | See http://sp.apps.bosch-iot-cloud.com/documentation/rest-api/rootcontroller-api-guide.html#_put_tenant_controller_v1_targetid_configdata # noqa 92 | 93 | Args: 94 | status_execution(ConfigStatusExecution): status of the action execution 95 | status_result(status_result): result of the action execution 96 | 97 | Keyword Args: 98 | action_id(str): Id of the action, not mandator for configData 99 | status_details((tuple, list)): List of details to provide 100 | other: passed as custom configuration data (key/value) 101 | """ 102 | assert isinstance(action_id, str), 'id must be string' 103 | assert isinstance(status_result, ConfigStatusResult), \ 104 | 'status_result_finished must be ConfigStatusResult enum' 105 | assert isinstance(status_execution, ConfigStatusExecution), \ 106 | 'status_execution must be ConfigStatusExecution enum' 107 | assert isinstance(status_details, (tuple, list)), \ 108 | 'status_details must be tuple or list' 109 | assert len(kwdata) > 0 110 | 111 | time = datetime.now().strftime('%Y%m%dT%H%M%S') 112 | 113 | put_data = { 114 | 'id': action_id, 115 | 'time': time, 116 | 'status': { 117 | 'result': { 118 | 'finished': status_result.name 119 | }, 120 | 'execution': status_execution.name, 121 | 'details': status_details 122 | }, 123 | 'data': kwdata 124 | } 125 | 126 | await self.put_resource('/{tenant}/controller/v1/{controllerId}/configData', put_data) 127 | 128 | 129 | def build_api_url(self, api_path): 130 | """ 131 | Build the actual API URL. 132 | 133 | Args: 134 | api_path(str): REST API path 135 | 136 | Returns: 137 | Expanded API URL with protocol (http/https) and host prepended 138 | """ 139 | protocol = 'https' if self.ssl else 'http' 140 | return '{protocol}://{host}/{api_path}'.format( 141 | protocol=protocol, host=self.host, api_path=api_path) 142 | 143 | async def get_resource(self, api_path, query_params={}, **kwargs): 144 | """ 145 | Helper method for HTTP GET API requests. 146 | 147 | Args: 148 | api_path(str): REST API path 149 | Keyword Args: 150 | query_params: Query parameters to add to the API URL 151 | kwargs: Other keyword args used for replacing items in the API path 152 | 153 | Returns: 154 | Response JSON data 155 | """ 156 | get_headers = { 157 | 'Accept': 'application/json', 158 | **self.headers 159 | } 160 | url = self.build_api_url( 161 | api_path.format( 162 | tenant=self.tenant, 163 | controllerId=self.controller_id, 164 | **kwargs)) 165 | 166 | self.logger.debug('GET {}'.format(url)) 167 | 168 | with async_timeout.timeout(self.timeout, loop=self.session.loop): 169 | async with self.session.get(url, headers=get_headers, 170 | params=query_params) as resp: 171 | await self.check_http_status(resp) 172 | json = await resp.json() 173 | self.logger.debug(json) 174 | return json 175 | 176 | async def get_binary_resource(self, api_path, dl_location, 177 | mime='application/octet-stream', 178 | chunk_size=512, timeout=3600, **kwargs): 179 | """ 180 | Helper method for binary HTTP GET API requests. 181 | 182 | Triggers download of the retreived content to ``dl_location``. 183 | 184 | Args: 185 | api_path(str): REST API path 186 | dl_location(str): storage path for downloaded artifact 187 | Keyword Args: 188 | mime: mimetype of content to retrieve 189 | (default: 'application/octet-stream') 190 | chunk_size: size of chunk to retrieve 191 | kwargs: Other keyword args used for replacing items in the API path 192 | 193 | Returns: 194 | MD5 hash of downloaded content 195 | """ 196 | url = self.build_api_url( 197 | api_path.format( 198 | tenant=self.tenant, 199 | controllerId=self.controller_id, 200 | **kwargs)) 201 | return await self.get_binary(url, dl_location, mime, chunk_size, 202 | timeout=timeout) 203 | 204 | async def get_binary(self, url, dl_location, 205 | mime='application/octet-stream', chunk_size=512, 206 | timeout=3600): 207 | """ 208 | Actual download method with checksum checking. 209 | 210 | Args: 211 | url(str): URL of item to download 212 | dl_location(str): storage path for downloaded artifact 213 | Keyword Args: 214 | mime: mimetype of content to retrieve 215 | (default: 'application/octet-stream') 216 | chunk_size: size of chunk to retrieve 217 | timeout: download timeout 218 | (default: 3600) 219 | 220 | Returns: 221 | MD5 hash of downloaded content 222 | """ 223 | get_bin_headers = { 224 | 'Accept': mime, 225 | **self.headers 226 | } 227 | hash_md5 = hashlib.md5() 228 | 229 | self.logger.debug('GET binary {}'.format(url)) 230 | with async_timeout.timeout(timeout, loop=self.session.loop): 231 | async with self.session.get(url, headers=get_bin_headers) as resp: 232 | await self.check_http_status(resp) 233 | with open(dl_location, 'wb') as fd: 234 | while True: 235 | with async_timeout.timeout(60): 236 | chunk = await resp.content.read(chunk_size) 237 | if not chunk: 238 | break 239 | fd.write(chunk) 240 | hash_md5.update(chunk) 241 | return hash_md5.hexdigest() 242 | 243 | async def post_resource(self, api_path, data, **kwargs): 244 | """ 245 | Helper method for HTTP POST API requests. 246 | 247 | Args: 248 | api_path(str): REST API path 249 | data: JSON data for POST request 250 | Keyword Args: 251 | kwargs: keyword args used for replacing items in the API path 252 | """ 253 | post_headers = { 254 | 'Content-Type': 'application/json', 255 | 'Accept': 'application/json', 256 | **self.headers 257 | } 258 | url = self.build_api_url( 259 | api_path.format( 260 | tenant=self.tenant, 261 | controllerId=self.controller_id, 262 | **kwargs)) 263 | self.logger.debug('POST {}'.format(url)) 264 | with async_timeout.timeout(self.timeout): 265 | async with self.session.post(url, headers=post_headers, 266 | data=json.dumps(data)) as resp: 267 | await self.check_http_status(resp) 268 | 269 | async def put_resource(self, api_path, data, **kwargs): 270 | """ 271 | Helper method for HTTP PUT API requests. 272 | 273 | Args: 274 | api_path(str): REST API path 275 | data: JSON data for POST request 276 | Keyword Args: 277 | kwargs: keyword args used for replacing items in the API path 278 | """ 279 | put_headers = { 280 | 'Content-Type': 'application/json', 281 | **self.headers 282 | } 283 | url = self.build_api_url( 284 | api_path.format( 285 | tenant=self.tenant, 286 | controllerId=self.controller_id, 287 | **kwargs)) 288 | self.logger.debug('PUT {}'.format(url)) 289 | self.logger.debug(json.dumps(data)) 290 | with async_timeout.timeout(self.timeout): 291 | async with self.session.put(url, headers=put_headers, 292 | data=json.dumps(data)) as resp: 293 | await self.check_http_status(resp) 294 | 295 | async def check_http_status(self, resp): 296 | """Log API error message.""" 297 | if resp.status != 200: 298 | error_description = await resp.text() 299 | if error_description: 300 | self.logger.debug('API error: {}'.format(error_description)) 301 | 302 | if resp.status in self.error_responses: 303 | reason = self.error_responses[resp.status] 304 | else: 305 | reason = resp.reason 306 | 307 | raise APIError('{status}: {reason}'.format( 308 | status=resp.status, reason=reason)) 309 | -------------------------------------------------------------------------------- /rauc_hawkbit/ddi/deployment_base.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from datetime import datetime 4 | from enum import Enum 5 | 6 | # status of the action execution 7 | DeploymentStatusExecution = Enum('DeploymentStatusExecution', 8 | 'closed proceeding canceled scheduled \ 9 | rejected resumed') 10 | 11 | # defined status of the result 12 | DeploymentStatusResult = Enum('DeploymentStatusResultFinished', 13 | 'success failure none') 14 | 15 | # handling for the update part of the provisioning process 16 | DeploymentUpdate = Enum('DeploymentUpdate', 17 | 'skip attempt forced') 18 | 19 | 20 | class DeploymentBaseAction(object): 21 | """ 22 | Represents /{tenant}/controller/v1/{targetid}/deploymentBase/{actionId} 23 | in HawkBit's DDI API. 24 | See http://sp.apps.bosch-iot-cloud.com/documentation/rest-api/rootcontroller-api-guide.html#_get_tenant_controller_v1_targetid_deploymentbase_actionid # noqa 25 | """ 26 | 27 | def __init__(self, ddi, action_id): 28 | self.ddi = ddi 29 | self.action_id = action_id 30 | 31 | async def __call__(self, resource=None): 32 | return await self.ddi.get_resource( 33 | '/{tenant}/controller/v1/{controllerId}/deploymentBase/{actionId}', {'c': resource}, actionId=self.action_id) 34 | 35 | async def feedback(self, status_execution, status_result, 36 | status_details=(), **kwstatus_result_progress): 37 | """ 38 | See http://sp.apps.bosch-iot-cloud.com/documentation/rest-api/rootcontroller-api-guide.html#_post_tenant_controller_v1_targetid_deploymentbase_actionid_feedback # noqa 39 | """ 40 | assert isinstance(status_execution, DeploymentStatusExecution), \ 41 | 'status_execution must be DeploymentStatusExecution enum' 42 | assert isinstance(status_result, DeploymentStatusResult), \ 43 | 'status_result must be DeploymentStatusResult enum' 44 | assert isinstance(status_details, (tuple, list)), \ 45 | 'status_details must be tuple or list' 46 | 47 | time = datetime.now().strftime('%Y%m%dT%H%M%S') 48 | 49 | post_data = { 50 | 'id': self.action_id, 51 | 'time': time, 52 | 'status': { 53 | 'result': { 54 | 'progress': kwstatus_result_progress, 55 | 'finished': status_result.name 56 | }, 57 | 'execution': status_execution.name, 58 | 'details': status_details 59 | } 60 | } 61 | 62 | return await self.ddi.post_resource( 63 | '/{tenant}/controller/v1/{controllerId}/deploymentBase/{actionId}/feedback', post_data, actionId=self.action_id) 64 | 65 | 66 | class DeploymentBase(object): 67 | """ 68 | Represents /{tenant}/controller/v1/{targetid}/deploymentBase in HawkBit's 69 | DDI API. 70 | """ 71 | def __init__(self, ddi): 72 | self.ddi = ddi 73 | 74 | def __getitem__(self, key): 75 | action_id = key 76 | return DeploymentBaseAction(self.ddi, action_id) 77 | -------------------------------------------------------------------------------- /rauc_hawkbit/ddi/softwaremodules.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | class FileName(object): 4 | """ 5 | Represents /{tenant}/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{fileName} # noqa 6 | in HawkBit's DDI API. 7 | """ 8 | def __init__(self, ddi, software_module_id, file_name): 9 | self.ddi = ddi 10 | self.software_module_id = software_module_id 11 | self.file_name = file_name 12 | 13 | async def __call__(self, bundle_dl_location): 14 | """ 15 | See http://sp.apps.bosch-iot-cloud.com/documentation/rest-api/rootcontroller-api-guide.html#_get_tenant_controller_v1_targetid_softwaremodules_softwaremoduleid_artifacts_filename # noqa 16 | """ 17 | return await self.ddi.get_binary_resource( 18 | '/{tenant}/controller/v1/{controllerId}/softwaremodules/{moduleId}/artifacts/{filename}', bundle_dl_location, moduleId=self.software_module_id, 19 | filename=self.file_name) 20 | 21 | async def MD5SUM(self, md5_dl_location): 22 | """ 23 | See http://sp.apps.bosch-iot-cloud.com/documentation/rest-api/rootcontroller-api-guide.html#_get_tenant_controller_v1_targetid_softwaremodules_softwaremoduleid_artifacts_filename_md5sum # noqa 24 | """ 25 | return await self.ddi.get_binary_resource( 26 | '/{tenant}/controller/v1/{controllerId}/softwaremodules/{moduleId}/artifacts/{filename}', md5_dl_location, mime='text/plain', moduleId=self.software_module_id, 27 | filename=self.file_name) 28 | 29 | 30 | class Artifacts(object): 31 | """ 32 | Represents /{tenant}/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts # noqa 33 | in HawkBit's DDI API. 34 | """ 35 | def __init__(self, ddi, software_module_id): 36 | self.ddi = ddi 37 | self.software_module_id = software_module_id 38 | 39 | async def __call__(self): 40 | """ 41 | See http://sp.apps.bosch-iot-cloud.com/documentation/rest-api/rootcontroller-api-guide.html#_get_tenant_controller_v1_targetid_softwaremodules_softwaremoduleid_artifacts # noqa 42 | """ 43 | return await self.ddi.get_resource( 44 | '/{tenant}/controller/v1/{controllerId}/softwaremodules/{moduleId}/artifacts', moduleId=self.software_module_id) 45 | 46 | def __getitem__(self, key): 47 | filename = key 48 | return FileName(self.ddi, self.software_module_id, filename) 49 | 50 | 51 | class SoftwareModule(object): 52 | """ 53 | Represents /{tenant}/controller/v1/{targetid}/softwaremodules/{softwareModuleId} # noqa 54 | in HawkBit's DDI API. 55 | """ 56 | def __init__(self, ddi, software_module_id): 57 | self.ddi = ddi 58 | self.software_module_id = software_module_id 59 | 60 | @property 61 | def artifacts(self): 62 | return Artifacts(self.ddi, self.software_module_id) 63 | 64 | 65 | class SoftwareModules(object): 66 | """ 67 | Represents /{tenant}/controller/v1/{targetid}/softwaremodules in 68 | HawkBit's DDI API. 69 | """ 70 | def __init__(self, ddi): 71 | self.ddi = ddi 72 | 73 | def __getitem__(self, software_module_id): 74 | return SoftwareModule(self.ddi, software_module_id) 75 | -------------------------------------------------------------------------------- /rauc_hawkbit/rauc_dbus_ddi_client.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import asyncio 4 | from aiohttp.client_exceptions import ClientOSError, ClientResponseError 5 | from gi.repository import GLib 6 | from datetime import datetime, timedelta 7 | import os 8 | import os.path 9 | import re 10 | import logging 11 | 12 | from .dbus_client import AsyncDBUSClient 13 | from .ddi.client import DDIClient, APIError 14 | from .ddi.client import ( 15 | ConfigStatusExecution, ConfigStatusResult) 16 | from .ddi.deployment_base import ( 17 | DeploymentStatusExecution, DeploymentStatusResult) 18 | from .ddi.cancel_action import ( 19 | CancelStatusExecution, CancelStatusResult) 20 | 21 | 22 | class RaucDBUSDDIClient(AsyncDBUSClient): 23 | """ 24 | Client broker communicating with RAUC via DBUS and HawkBit DDI HTTP 25 | interface. 26 | """ 27 | def __init__(self, session, host, ssl, tenant_id, target_name, auth_token, 28 | attributes, bundle_dl_location, result_callback, step_callback=None, lock_keeper=None): 29 | super(RaucDBUSDDIClient, self).__init__() 30 | 31 | self.attributes = attributes 32 | 33 | self.logger = logging.getLogger('rauc_hawkbit') 34 | self.ddi = DDIClient(session, host, ssl, auth_token, tenant_id, target_name) 35 | self.action_id = None 36 | 37 | bundle_dir = os.path.dirname(bundle_dl_location) 38 | assert os.path.isdir(bundle_dir), 'Bundle directory must exist' 39 | assert os.access(bundle_dir, os.W_OK), 'Bundle directory not writeable' 40 | 41 | self.bundle_dl_location = bundle_dl_location 42 | self.lock_keeper = lock_keeper 43 | self.result_callback = result_callback 44 | self.step_callback = step_callback 45 | 46 | # DBUS proxy 47 | self.rauc = self.new_proxy('de.pengutronix.rauc.Installer', '/') 48 | 49 | # DBUS property/signal subscription 50 | self.new_property_subscription('de.pengutronix.rauc.Installer', 51 | 'Progress', self.progress_callback) 52 | self.new_property_subscription('de.pengutronix.rauc.Installer', 53 | 'LastError', self.last_error_callback) 54 | self.new_signal_subscription('de.pengutronix.rauc.Installer', 55 | 'Completed', self.complete_callback) 56 | 57 | async def complete_callback(self, connection, sender_name, object_path, 58 | interface_name, signal_name, parameters): 59 | """Callback for completion.""" 60 | # bundle update was triggered from elsewhere 61 | if not self.action_id: 62 | return 63 | 64 | if self.lock_keeper: 65 | self.lock_keeper.unlock(self) 66 | 67 | result = parameters[0] 68 | os.remove(self.bundle_dl_location) 69 | status_msg = 'Rauc bundle update completed with result: {}'.format( 70 | result) 71 | self.logger.info(status_msg) 72 | 73 | # send feedback to HawkBit 74 | if result == 0: 75 | status_execution = DeploymentStatusExecution.closed 76 | status_result = DeploymentStatusResult.success 77 | else: 78 | status_execution = DeploymentStatusExecution.closed 79 | status_result = DeploymentStatusResult.failure 80 | 81 | await self.ddi.deploymentBase[self.action_id].feedback( 82 | status_execution, status_result, [status_msg]) 83 | 84 | self.action_id = None 85 | 86 | self.result_callback(result) 87 | 88 | async def progress_callback(self, connection, sender_name, 89 | object_path, interface_name, 90 | signal_name, parameters): 91 | """Callback for changed Progress property.""" 92 | # bundle update was triggered from elsewhere 93 | if not self.action_id: 94 | return 95 | 96 | percentage, description, nesting_depth = parameters 97 | self.logger.info('Update progress: {}% {}'.format(percentage, 98 | description)) 99 | 100 | if self.step_callback: 101 | self.step_callback(percentage, description) 102 | 103 | # send feedback to HawkBit 104 | status_execution = DeploymentStatusExecution.proceeding 105 | status_result = DeploymentStatusResult.none 106 | await self.ddi.deploymentBase[self.action_id].feedback( 107 | status_execution, status_result, [description], 108 | percentage=percentage) 109 | 110 | async def last_error_callback(self, connection, sender_name, 111 | object_path, interface_name, 112 | signal_name, last_error): 113 | """Callback for changed LastError property.""" 114 | # bundle update was triggered from elsewhere 115 | if not self.action_id: 116 | return 117 | 118 | # LastError property might have been cleared 119 | if not last_error: 120 | return 121 | 122 | self.logger.info('Last error: {}'.format(last_error)) 123 | 124 | # send feedback to HawkBit 125 | status_execution = DeploymentStatusExecution.proceeding 126 | status_result = DeploymentStatusResult.failure 127 | await self.ddi.deploymentBase[self.action_id].feedback( 128 | status_execution, status_result, [last_error]) 129 | 130 | async def start_polling(self, wait_on_error=60): 131 | """Wrapper around self.poll_base_resource() for exception handling.""" 132 | while True: 133 | try: 134 | await self.poll_base_resource() 135 | except asyncio.CancelledError: 136 | self.logger.info('Polling cancelled') 137 | break 138 | except asyncio.TimeoutError: 139 | self.logger.warning('Polling failed due to TimeoutError') 140 | except (APIError, TimeoutError, ClientOSError, ClientResponseError) as e: 141 | # log error and start all over again 142 | self.logger.warning('Polling failed with a temporary error: {}'.format(e)) 143 | except: 144 | self.logger.exception('Polling failed with an unexpected exception:') 145 | self.action_id = None 146 | self.logger.info('Retry will happen in {} seconds'.format( 147 | wait_on_error)) 148 | await asyncio.sleep(wait_on_error) 149 | 150 | async def identify(self, base): 151 | """Identify target against HawkBit.""" 152 | self.logger.info('Sending identifying information to HawkBit') 153 | # identify 154 | await self.ddi.configData( 155 | ConfigStatusExecution.closed, 156 | ConfigStatusResult.success, **self.attributes) 157 | 158 | async def cancel(self, base): 159 | self.logger.info('Received cancelation request') 160 | # retrieve action id from URL 161 | deployment = base['_links']['cancelAction']['href'] 162 | match = re.search('/cancelAction/(.+)$', deployment) 163 | action_id, = match.groups() 164 | # retrieve stop_id 165 | stop_info = await self.ddi.cancelAction[action_id]() 166 | stop_id = stop_info['cancelAction']['stopId'] 167 | # Reject cancel request 168 | self.logger.info('Rejecting cancelation request') 169 | await self.ddi.cancelAction[stop_id].feedback( 170 | CancelStatusExecution.rejected, CancelStatusResult.success, status_details=("Cancelling not supported",)) 171 | 172 | async def install(self): 173 | if self.lock_keeper and not self.lock_keeper.lock(self): 174 | self.logger.info("Another installation is already in progress, aborting") 175 | return 176 | 177 | self.rauc.Install('(s)', self.bundle_dl_location) 178 | 179 | async def process_deployment(self, base): 180 | """ 181 | Check for deployments, download them, verify checksum and trigger 182 | RAUC install operation. 183 | """ 184 | if self.action_id is not None: 185 | self.logger.info('Deployment is already in progress') 186 | return 187 | 188 | # retrieve action id and resource parameter from URL 189 | deployment = base['_links']['deploymentBase']['href'] 190 | match = re.search('/deploymentBase/(.+)\?c=(.+)$', deployment) 191 | action_id, resource = match.groups() 192 | self.logger.info('Deployment found for this target') 193 | # fetch deployment information 194 | deploy_info = await self.ddi.deploymentBase[action_id](resource) 195 | try: 196 | chunk = deploy_info['deployment']['chunks'][0] 197 | except IndexError: 198 | # send negative feedback to HawkBit 199 | status_execution = DeploymentStatusExecution.closed 200 | status_result = DeploymentStatusResult.failure 201 | msg = 'Deployment without chunks found. Ignoring' 202 | await self.ddi.deploymentBase[action_id].feedback( 203 | status_execution, status_result, [msg]) 204 | raise APIError(msg) 205 | 206 | try: 207 | artifact = chunk['artifacts'][0] 208 | except IndexError: 209 | # send negative feedback to HawkBit 210 | status_execution = DeploymentStatusExecution.closed 211 | status_result = DeploymentStatusResult.failure 212 | msg = 'Deployment without artifacts found. Ignoring' 213 | await self.ddi.deploymentBase[action_id].feedback( 214 | status_execution, status_result, [msg]) 215 | raise APIError(msg) 216 | 217 | # prefer https ('download') over http ('download-http') 218 | # HawkBit provides either only https, only http or both 219 | if 'download' in artifact['_links']: 220 | download_url = artifact['_links']['download']['href'] 221 | else: 222 | download_url = artifact['_links']['download-http']['href'] 223 | 224 | # download artifact, check md5 and report feedback 225 | md5_hash = artifact['hashes']['md5'] 226 | self.logger.info('Starting bundle download') 227 | await self.download_artifact(action_id, download_url, md5_hash) 228 | 229 | # download successful, start install 230 | self.logger.info('Starting installation') 231 | try: 232 | self.action_id = action_id 233 | # do not interrupt install call 234 | await asyncio.shield(self.install()) 235 | except GLib.Error as e: 236 | # send negative feedback to HawkBit 237 | status_execution = DeploymentStatusExecution.closed 238 | status_result = DeploymentStatusResult.failure 239 | await self.ddi.deploymentBase[action_id].feedback( 240 | status_execution, status_result, [str(e)]) 241 | raise APIError(str(e)) 242 | 243 | async def download_artifact(self, action_id, url, md5sum, 244 | tries=3): 245 | """Download bundle artifact.""" 246 | try: 247 | match = re.search('/softwaremodules/(.+)/artifacts/(.+)$', url) 248 | software_module, filename = match.groups() 249 | static_api_url = False 250 | except AttributeError: 251 | static_api_url = True 252 | 253 | if self.step_callback: 254 | self.step_callback(0, "Downloading bundle...") 255 | 256 | # try several times 257 | for dl_try in range(tries): 258 | if not static_api_url: 259 | checksum = await self.ddi.softwaremodules[software_module] \ 260 | .artifacts[filename](self.bundle_dl_location) 261 | else: 262 | # API implementations might return static URLs, so bypass API 263 | # methods and download bundle anyway 264 | checksum = await self.ddi.get_binary(url, 265 | self.bundle_dl_location) 266 | 267 | if checksum == md5sum: 268 | self.logger.info('Download successful') 269 | return 270 | else: 271 | self.logger.error('Checksum does not match. {} tries remaining' 272 | .format(tries-dl_try)) 273 | # MD5 comparison unsuccessful, send negative feedback to HawkBit 274 | status_msg = 'Artifact checksum does not match after {} tries.' \ 275 | .format(tries) 276 | status_execution = DeploymentStatusExecution.closed 277 | status_result = DeploymentStatusResult.failure 278 | await self.ddi.deploymentBase[action_id].feedback( 279 | status_execution, status_result, [status_msg]) 280 | raise APIError(status_msg) 281 | 282 | async def sleep(self, base): 283 | """Sleep time suggested by HawkBit.""" 284 | sleep_str = base['config']['polling']['sleep'] 285 | self.logger.info('Will sleep for {}'.format(sleep_str)) 286 | t = datetime.strptime(sleep_str, '%H:%M:%S') 287 | delta = timedelta(hours=t.hour, minutes=t.minute, seconds=t.second) 288 | await asyncio.sleep(delta.total_seconds()) 289 | 290 | async def poll_base_resource(self): 291 | """Poll DDI API base resource.""" 292 | while True: 293 | base = await self.ddi() 294 | 295 | if '_links' in base: 296 | if 'configData' in base['_links']: 297 | await self.identify(base) 298 | if 'deploymentBase' in base['_links']: 299 | await self.process_deployment(base) 300 | if 'cancelAction' in base['_links']: 301 | await self.cancel(base) 302 | 303 | await self.sleep(base) 304 | -------------------------------------------------------------------------------- /scripts/send_feedback.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | CONTAINER_NAME=$1 4 | SOCKET_PATH="/tmp/fullmetalupdate/fullmetalupdate_notify_${CONTAINER_NAME}.sock" 5 | 6 | msg="success" 7 | test -z ${EXIT_CODE} || msg="${SERVICE_RESULT} ${EXIT_CODE} ${EXIT_STATUS}" 8 | 9 | test -e ${SOCKET_PATH} && \ 10 | echo ${msg} | socat - UNIX-CONNECT:${SOCKET_PATH} 11 | 12 | exit 0 13 | --------------------------------------------------------------------------------