├── .codecov.yml
├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── cmd
├── agent
│ └── main.go
└── configure
│ ├── main.go
│ └── main_test.go
├── config
├── config.go
└── config_test.go
├── docs
└── IoTManagement.svg
├── go.mod
├── go.sum
├── identity
├── identity.go
├── identity_test.go
└── store.go
├── mqtt
├── metrics.go
├── mqtt.go
├── mqtt_test.go
├── subscribe.go
├── subscribe_action.go
└── testing_client.go
├── run-checks
├── snap
├── hooks
│ └── configure
└── snapcraft.yaml
└── snapdapi
├── assert.go
├── client.go
└── testing_client.go
/.codecov.yml:
--------------------------------------------------------------------------------
1 | ignore:
2 | - "testing_*.go"
3 | - "./**/testing_*.go"
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .coverage/
2 | .idea/
3 | .secret
4 | main
5 | vendor/*/
6 |
7 | # Snapcraft
8 | *.snap
9 | parts/
10 | prime/
11 | stage/
12 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: go
2 | go_import_path: github.com/canonical/iot-agent
3 | go:
4 | - 1.12
5 | env:
6 | matrix:
7 | - TEST_SUITE="--static"
8 | - TEST_SUITE="--unit"
9 |
10 | before_install:
11 | - go get golang.org/x/lint/golint
12 |
13 | install:
14 | - echo $GOPATH
15 | - echo "Remaining install is done by the test script."
16 | - true
17 | script: sh -v ./run-checks $TEST_SUITE
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [![Build Status][travis-image]][travis-url]
2 | [![Go Report Card][goreportcard-image]][goreportcard-url]
3 | [![codecov][codecov-image]][codecov-url]
4 | # IoT Agent
5 |
6 | The IoT Agent enrolls a device with the [IoT Identity](https://github.com/canonical/iot-identity) service and
7 | receives credentials to access the MQTT broker. Via MQTT, it establishes communication with
8 | an [IoT Management](https://github.com/canonical/iot-management) service, so the device can be remotely monitored and managed over a
9 | secure connection. The state of the device is mirrored in the cloud by the [IoT Device Twin](https://github.com/canonical/iot-devicetwin) service.
10 |
11 | The agent is intended to operate on a device running Ubuntu or Ubuntu Core with snapd enabled.
12 | The device management features are implemented using the snapd REST API.
13 |
14 | 
15 |
16 |
17 | ## Build
18 | The project uses vendorized dependencies using govendor. Development has been done on minimum Go version 1.12.1.
19 | ```bash
20 | $ cd iot-agent
21 | $ go mod tidy
22 | $ go build cmd/agent/main.go
23 | $ go build cmd/configure/main.go
24 | ```
25 |
26 | ## Connect Interfaces
27 | iot-agent uses snapd-control interface which is super powerful. Only the private IoT App Store (aka Brand Store) owners can
28 | automatically connect the mentioned interface. To use the iot-agent, one can either install it with --devmode or manually connect
29 | snapd-control interface. Please note that a snap with snapd-control interface can not be uploaded to the Global Snap Store. iot-agent
30 | snap is an exception for demonstrating purposes.
31 |
32 | ```bash
33 | $ snap connect iot-agent:snapd-control :snapd-control
34 | ```
35 |
36 |
37 | ## Run
38 | ```bash
39 | go run cmd/agent/main.go -help
40 | -credentials string
41 | The full path to the credentials file (default ".secret")
42 | -url string
43 | The URL of the Identity Service (default "http://localhost:8030/")
44 | ```
45 |
46 | ## Contributing
47 | Before contributing you should sign [Canonical's contributor agreement](https://www.ubuntu.com/legal/contributors), it’s the easiest way for you to give us permission to use your contributions.
48 |
49 | [travis-image]: https://travis-ci.org/canonical/iot-agent.svg?branch=master
50 | [travis-url]: https://travis-ci.org/canonical/iot-agent
51 | [goreportcard-image]: https://goreportcard.com/badge/github.com/canonical/iot-agent
52 | [goreportcard-url]: https://goreportcard.com/report/github.com/canonical/iot-agent
53 | [codecov-url]: https://codecov.io/gh/canonical/iot-agent
54 | [codecov-image]: https://codecov.io/gh/canonical/iot-agent/branch/master/graph/badge.svg
55 |
--------------------------------------------------------------------------------
/cmd/agent/main.go:
--------------------------------------------------------------------------------
1 | // -*- Mode: Go; indent-tabs-mode: t -*-
2 |
3 | /*
4 | * This file is part of the IoT Agent
5 | * Copyright 2019 Canonical Ltd.
6 | *
7 | * This program is free software: you can redistribute it and/or modify it
8 | * under the terms of the GNU General Public License version 3, as
9 | * published by the Free Software Foundation.
10 | *
11 | * This program is distributed in the hope that it will be useful, but WITHOUT
12 | * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
13 | * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.
14 | * See the GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | package main
21 |
22 | import (
23 | "github.com/canonical/iot-agent/mqtt"
24 | "github.com/canonical/iot-agent/snapdapi"
25 | "log"
26 | "time"
27 |
28 | "github.com/canonical/iot-agent/config"
29 | "github.com/canonical/iot-agent/identity"
30 | )
31 |
32 | const tickInterval = 60
33 |
34 | var mqttConn *mqtt.Connection
35 |
36 | func main() {
37 | log.Println("Starting IoT agent")
38 |
39 | // Set up the dependency chain
40 | settings := config.ReadParameters()
41 | snap := snapdapi.NewClientAdapter()
42 |
43 | defer mqttConn.Close()
44 |
45 | // On an interval...
46 | ticker := time.NewTicker(time.Second * tickInterval)
47 | for range ticker.C {
48 | // Check that we are enrolled with the identity service
49 | idSrv := identity.NewService(settings, snap)
50 | enroll, err := idSrv.CheckEnrollment()
51 | if err != nil {
52 | log.Printf("Error with enrollment: %v", err)
53 | continue
54 | }
55 |
56 | // Create/get the MQTT connection
57 | mqttConn, err = mqtt.GetConnection(enroll)
58 | if err != nil {
59 | log.Printf("Error with MQTT connection: %v", err)
60 | continue
61 | }
62 |
63 | // Publish the health check and metrics messages
64 | mqttConn.Health()
65 | mqttConn.Metrics()
66 | }
67 | ticker.Stop()
68 | }
69 |
--------------------------------------------------------------------------------
/cmd/configure/main.go:
--------------------------------------------------------------------------------
1 | // -*- Mode: Go; indent-tabs-mode: t -*-
2 |
3 | /*
4 | * This file is part of the IoT Agent
5 | * Copyright 2019 Canonical Ltd.
6 | *
7 | * This program is free software: you can redistribute it and/or modify it
8 | * under the terms of the GNU General Public License version 3, as
9 | * published by the Free Software Foundation.
10 | *
11 | * This program is distributed in the hope that it will be useful, but WITHOUT
12 | * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
13 | * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.
14 | * See the GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | package main
21 |
22 | import (
23 | "flag"
24 | "fmt"
25 | "github.com/canonical/iot-agent/config"
26 | "os"
27 | )
28 |
29 | func main() {
30 | var (
31 | url string
32 | credsPath string
33 | )
34 | flag.StringVar(&url, "url", config.DefaultIdentityURL, "The URL of the Identity Service")
35 | flag.StringVar(&credsPath, "path", config.GetPath(config.DefaultCredentialsPath), "The full path to the credentials file")
36 | flag.Parse()
37 |
38 | // Store the URL (let the other parameters be defaulted)
39 | err := config.StoreParameters(config.Settings{
40 | IdentityURL: url,
41 | })
42 | if err != nil {
43 | fmt.Println("Error saving parameters:", err)
44 | os.Exit(1)
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/cmd/configure/main_test.go:
--------------------------------------------------------------------------------
1 | // -*- Mode: Go; indent-tabs-mode: t -*-
2 |
3 | /*
4 | * This file is part of the IoT Agent
5 | * Copyright 2019 Canonical Ltd.
6 | *
7 | * This program is free software: you can redistribute it and/or modify it
8 | * under the terms of the GNU General Public License version 3, as
9 | * published by the Free Software Foundation.
10 | *
11 | * This program is distributed in the hope that it will be useful, but WITHOUT
12 | * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
13 | * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.
14 | * See the GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | package main
21 |
22 | import (
23 | "github.com/canonical/iot-agent/config"
24 | "os"
25 | "testing"
26 | )
27 |
28 | func Test_main(t *testing.T) {
29 | tests := []struct {
30 | name string
31 | }{
32 | {"valid"},
33 | }
34 | for _, tt := range tests {
35 | t.Run(tt.name, func(t *testing.T) {
36 | main()
37 |
38 | got := config.ReadParameters()
39 | if got.IdentityURL != config.DefaultIdentityURL {
40 | t.Errorf("Config.ReadParameters() got = %v, want %v", got.IdentityURL, config.DefaultIdentityURL)
41 | }
42 | if got.CredentialsPath != config.DefaultCredentialsPath {
43 | t.Errorf("Config.ReadParameters() got = %v, want %v", got.CredentialsPath, config.DefaultCredentialsPath)
44 | }
45 |
46 | _ = os.Remove("params")
47 | })
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/config/config.go:
--------------------------------------------------------------------------------
1 | // -*- Mode: Go; indent-tabs-mode: t -*-
2 |
3 | /*
4 | * This file is part of the IoT Agent
5 | * Copyright 2019 Canonical Ltd.
6 | *
7 | * This program is free software: you can redistribute it and/or modify it
8 | * under the terms of the GNU General Public License version 3, as
9 | * published by the Free Software Foundation.
10 | *
11 | * This program is distributed in the hope that it will be useful, but WITHOUT
12 | * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
13 | * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.
14 | * See the GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | package config
21 |
22 | import (
23 | "encoding/json"
24 | "io/ioutil"
25 | "log"
26 | "os"
27 | "path"
28 | )
29 |
30 | // Default parameters
31 | const (
32 | DefaultIdentityURL = "http://localhost:8030/"
33 | DefaultCredentialsPath = ".secret"
34 | paramsEnvVar = "SNAP_DATA"
35 | paramsFilename = "params"
36 | )
37 |
38 | // Settings defines the application configuration
39 | type Settings struct {
40 | IdentityURL string `json:"url"`
41 | CredentialsPath string `json:"path"`
42 | }
43 |
44 | // Config holds the config parameters for the application
45 | var Config Settings
46 |
47 | // ReadParameters fetches the store config parameters
48 | func ReadParameters() *Settings {
49 | Config = Settings{
50 | IdentityURL: DefaultIdentityURL,
51 | CredentialsPath: GetPath(DefaultCredentialsPath),
52 | }
53 |
54 | p := GetPath(paramsFilename)
55 |
56 | dat, err := ioutil.ReadFile(p)
57 | if err != nil {
58 | log.Printf("Error reading config parameters: %v", err)
59 | _ = StoreParameters(Config)
60 | return &Config
61 | }
62 |
63 | err = json.Unmarshal(dat, &Config)
64 | if err != nil {
65 | log.Printf("Error parsing config parameters: %v", err)
66 | return &Config
67 | }
68 |
69 | return &Config
70 | }
71 |
72 | // StoreParameters stores the configuration parameters on the filesystem
73 | func StoreParameters(c Settings) error {
74 | p := GetPath(paramsFilename)
75 |
76 | // Default empty parameters
77 | if len(c.IdentityURL) == 0 {
78 | c.IdentityURL = DefaultIdentityURL
79 | }
80 | if len(c.CredentialsPath) == 0 {
81 | c.CredentialsPath = GetPath(DefaultCredentialsPath)
82 | }
83 |
84 | // Create the output file
85 | f, err := os.Create(p)
86 | if err != nil {
87 | return err
88 | }
89 | defer f.Close()
90 |
91 | // Convert the parameters to JSON
92 | b, err := json.Marshal(c)
93 | if err != nil {
94 | log.Printf("Error marshalling config parameters: %v", err)
95 | return err
96 | }
97 |
98 | // Output the JSON to the file
99 | _, err = f.Write(b)
100 | if err != nil {
101 | log.Printf("Error storing config parameters: %v", err)
102 | return err
103 | }
104 | _ = f.Sync()
105 |
106 | // Restrict access to the file
107 | return os.Chmod(p, 0600)
108 | }
109 |
110 | // GetPath returns the full path to the data file
111 | func GetPath(filename string) string {
112 | if len(os.Getenv(paramsEnvVar)) > 0 {
113 | return path.Join(os.Getenv(paramsEnvVar), "../current", filename)
114 | }
115 | return filename
116 | }
117 |
--------------------------------------------------------------------------------
/config/config_test.go:
--------------------------------------------------------------------------------
1 | // -*- Mode: Go; indent-tabs-mode: t -*-
2 |
3 | /*
4 | * This file is part of the IoT Agent
5 | * Copyright 2019 Canonical Ltd.
6 | *
7 | * This program is free software: you can redistribute it and/or modify it
8 | * under the terms of the GNU General Public License version 3, as
9 | * published by the Free Software Foundation.
10 | *
11 | * This program is distributed in the hope that it will be useful, but WITHOUT
12 | * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
13 | * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.
14 | * See the GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | package config
21 |
22 | import (
23 | "os"
24 | "testing"
25 | )
26 |
27 | func TestReadParameters(t *testing.T) {
28 | tests := []struct {
29 | name string
30 | }{
31 | {"default-settings-create"},
32 | }
33 | for _, tt := range tests {
34 | t.Run(tt.name, func(t *testing.T) {
35 | {
36 | got := ReadParameters()
37 | if got.IdentityURL != DefaultIdentityURL {
38 | t.Errorf("Config.ReadParameters() got = %v, want %v", got.IdentityURL, DefaultIdentityURL)
39 | }
40 | if got.CredentialsPath != DefaultCredentialsPath {
41 | t.Errorf("Config.ReadParameters() got = %v, want %v", got.CredentialsPath, DefaultCredentialsPath)
42 | }
43 |
44 | _ = os.Remove(paramsFilename)
45 | }
46 | })
47 | }
48 | }
49 |
50 | func TestStoreParameters(t *testing.T) {
51 | tests := []struct {
52 | name string
53 | args Settings
54 | wantErr bool
55 | }{
56 | {"valid", Settings{}, false},
57 | }
58 | for _, tt := range tests {
59 | t.Run(tt.name, func(t *testing.T) {
60 | if err := StoreParameters(tt.args); (err != nil) != tt.wantErr {
61 | t.Errorf("StoreParameters() error = %v, wantErr %v", err, tt.wantErr)
62 | }
63 |
64 | got := ReadParameters()
65 | if got.IdentityURL != DefaultIdentityURL {
66 | t.Errorf("Config.ReadParameters() got = %v, want %v", got.IdentityURL, DefaultIdentityURL)
67 | }
68 | if got.CredentialsPath != DefaultCredentialsPath {
69 | t.Errorf("Config.ReadParameters() got = %v, want %v", got.CredentialsPath, DefaultCredentialsPath)
70 | }
71 |
72 | _ = os.Remove(paramsFilename)
73 | })
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/docs/IoTManagement.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/canonical/iot-agent
2 |
3 | go 1.12
4 |
5 | require (
6 | github.com/StackExchange/wmi v0.0.0-20210224194228-fe8f1750fd46 // indirect
7 | github.com/canonical/iot-devicetwin v0.0.0-20191209143221-cc86588895e0
8 | github.com/canonical/iot-identity v0.0.0-20210408072605-83f114f75fbe
9 | github.com/eclipse/paho.mqtt.golang v1.2.0
10 | github.com/go-ole/go-ole v1.2.5 // indirect
11 | github.com/shirou/gopsutil v3.21.3+incompatible
12 | github.com/snapcore/snapd v0.0.0-20210407110058-e36434b3d408
13 | github.com/tklauser/go-sysconf v0.3.5 // indirect
14 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
15 | )
16 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/StackExchange/wmi v0.0.0-20210224194228-fe8f1750fd46 h1:5sXbqlSomvdjlRbWyNqkPsJ3Fg+tQZCbgeX1VGljbQY=
2 | github.com/StackExchange/wmi v0.0.0-20210224194228-fe8f1750fd46/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg=
3 | github.com/canonical/iot-devicetwin v0.0.0-20191209143221-cc86588895e0 h1:/9iMb+H4toE9KBBgK4T1CM1G1NWDYVaDtKrxtUGTclI=
4 | github.com/canonical/iot-devicetwin v0.0.0-20191209143221-cc86588895e0/go.mod h1:hReprL/L7BwtU93mFbWzH1HtOjZq2dnwWPoSAZdhBeA=
5 | github.com/canonical/iot-identity v0.0.0-20210408072605-83f114f75fbe h1:KMVs5N8VkooNj5ByqHQ376rZAc8rNkI3U07BPKyXlmI=
6 | github.com/canonical/iot-identity v0.0.0-20210408072605-83f114f75fbe/go.mod h1:Q7paRFEZrEtaGYlMBgKVTNi4GVQcwh4BUzFmIPyJ8ow=
7 | github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf h1:iW4rZ826su+pqaw19uhpSCzhj44qo35pNgKFGqzDKkU=
8 | github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
9 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
10 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
11 | github.com/eclipse/paho.mqtt.golang v1.2.0 h1:1F8mhG9+aO5/xpdtFkW4SxOJB67ukuDC3t2y2qayIX0=
12 | github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts=
13 | github.com/go-ole/go-ole v1.2.5 h1:t4MGB5xEDZvXI+0rMjjsfBsD7yAgp/s9ZDkL1JndXwY=
14 | github.com/go-ole/go-ole v1.2.5/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
15 | github.com/godbus/dbus v4.1.0+incompatible h1:WqqLRTsQic3apZUK9qC5sGNfXthmPXzUZ7nQPrNITa4=
16 | github.com/godbus/dbus v4.1.0+incompatible/go.mod h1:/YcGZj5zSblfDWMMoOzV4fas9FZnQYTkDnsGvmh2Grw=
17 | github.com/gorilla/mux v0.0.0-20190316133243-c5c6c98bc253 h1:NJmEBlYT+frGsjS+N/RFoptdOQrTtG0Ja+r0oi+amgg=
18 | github.com/gorilla/mux v0.0.0-20190316133243-c5c6c98bc253/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
19 | github.com/lib/pq v0.0.0-20190326042056-d6156e141ac6/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
20 | github.com/mvo5/goconfigparser v0.0.0-20201015074339-50f22f44deb5 h1:IUtr2a2HkY+0BPb4bz7t7+p26kmp366dLSkuAodXE10=
21 | github.com/mvo5/goconfigparser v0.0.0-20201015074339-50f22f44deb5/go.mod h1:xmt4k1xLDl8Tdan+0S/jmMK2uSUBSzTc18+5GN5Vea8=
22 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
23 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
24 | github.com/segmentio/ksuid v1.0.3 h1:FoResxvleQwYiPAVKe1tMUlEirodZqlqglIuFsdDntY=
25 | github.com/segmentio/ksuid v1.0.3/go.mod h1:/XUiZBD3kVx5SmUOl55voK5yeAbBNNIed+2O73XgrPE=
26 | github.com/shirou/gopsutil v3.21.3+incompatible h1:uenXGGa8ESCQq+dbgtl916dmg6PSAz2cXov0uORQ9v8=
27 | github.com/shirou/gopsutil v3.21.3+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
28 | github.com/snapcore/go-gettext v0.0.0-20201130093759-38740d1bd3d2 h1:nETXPg0CiJrMAwC2gqkcam9BiBWYGvTsSYRfrjOz2Kg=
29 | github.com/snapcore/go-gettext v0.0.0-20201130093759-38740d1bd3d2/go.mod h1:D3SsWAXK7wCCBZu+Vk5hc1EuKj/L3XN1puEMXTU4LrQ=
30 | github.com/snapcore/snapd v0.0.0-20210316092951-71c2f53833de/go.mod h1:3xrn7QDDKymcE5VO2rgWEQ5ZAUGb9htfwlXnoel6Io8=
31 | github.com/snapcore/snapd v0.0.0-20210407110058-e36434b3d408 h1:E+sBT1waF2L/RI67DYSyXKrVvBf3udcUK8GjRbtdkUU=
32 | github.com/snapcore/snapd v0.0.0-20210407110058-e36434b3d408/go.mod h1:3xrn7QDDKymcE5VO2rgWEQ5ZAUGb9htfwlXnoel6Io8=
33 | github.com/snapcore/squashfuse v0.0.0-20171220165323-319f6d41a041 h1:rzu8Xf5QoMJfOPf4giWLfbgvkt7dPbdTZCb80PPAALo=
34 | github.com/snapcore/squashfuse v0.0.0-20171220165323-319f6d41a041/go.mod h1:8loYitFPSdoeCXBs/XjO0fyGcpgLAybOHLUsGwgMq90=
35 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
36 | github.com/stretchr/testify v0.0.0-20190311161405-34c6fa2dc709 h1:zN7m1FsHm1PeW8oJ3JvZPC5Cc1lWnEiHtS1i6DpXcm0=
37 | github.com/stretchr/testify v0.0.0-20190311161405-34c6fa2dc709/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
38 | github.com/tklauser/go-sysconf v0.3.5 h1:uu3Xl4nkLzQfXNsWn15rPc/HQCJKObbt1dKJeWp3vU4=
39 | github.com/tklauser/go-sysconf v0.3.5/go.mod h1:MkWzOF4RMCshBAMXuhXJs64Rte09mITnppBXY/rYEFI=
40 | github.com/tklauser/numcpus v0.2.2 h1:oyhllyrScuYI6g+h/zUvNXNp1wy7x8qQy3t/piefldA=
41 | github.com/tklauser/numcpus v0.2.2/go.mod h1:x3qojaO3uyYt0i56EW/VUYs7uBvdl2fkfZFu0T9wgjM=
42 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
43 | golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c h1:Vj5n4GlwjmQteupaxJ9+0FNOmBrHfq7vN4btdGoDZgI=
44 | golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
45 | golang.org/x/net v0.0.0-20190328230028-74de082e2cca h1:hyA6yiAgbUwuWqtscNvWAI7U1CtlaD1KilQ6iudt1aI=
46 | golang.org/x/net v0.0.0-20190328230028-74de082e2cca/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
47 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
48 | golang.org/x/sys v0.0.0-20190329044733-9eb1bfa1ce65/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
49 | golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
50 | golang.org/x/sys v0.0.0-20210316164454-77fc1eacc6aa h1:ZYxPR6aca/uhfRJyaOAtflSHjJYiktO7QnJC5ut7iY4=
51 | golang.org/x/sys v0.0.0-20210316164454-77fc1eacc6aa/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
52 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
53 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
54 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
55 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
56 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
57 | gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 h1:yiW+nvdHb9LVqSHQBXfZCieqV4fzYhNBql77zY0ykqs=
58 | gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637/go.mod h1:BHsqpu/nsuzkT5BpiH1EMZPLyqSMM8JbIavyFACoFNk=
59 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
60 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
61 |
--------------------------------------------------------------------------------
/identity/identity.go:
--------------------------------------------------------------------------------
1 | // -*- Mode: Go; indent-tabs-mode: t -*-
2 |
3 | /*
4 | * This file is part of the IoT Agent
5 | * Copyright 2019 Canonical Ltd.
6 | *
7 | * This program is free software: you can redistribute it and/or modify it
8 | * under the terms of the GNU General Public License version 3, as
9 | * published by the Free Software Foundation.
10 | *
11 | * This program is distributed in the hope that it will be useful, but WITHOUT
12 | * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
13 | * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.
14 | * See the GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | package identity
21 |
22 | import (
23 | "bytes"
24 | "encoding/base64"
25 | "encoding/json"
26 | "fmt"
27 | "io"
28 | "io/ioutil"
29 | "net/http"
30 | "net/url"
31 | "os"
32 | "path"
33 |
34 | "github.com/canonical/iot-agent/config"
35 | "github.com/canonical/iot-agent/snapdapi"
36 | "github.com/canonical/iot-identity/domain"
37 | "github.com/canonical/iot-identity/web"
38 | )
39 |
40 | // Default parameters
41 | const (
42 | mediaType = "application/x.ubuntu.assertion"
43 | commonDataEnvVar = "SNAP_COMMON"
44 | deviceDataFileName = "device-data.bin"
45 | )
46 |
47 | // UseCase is the interface for the identity service use cases
48 | type UseCase interface {
49 | CheckEnrollment() (*domain.Enrollment, error)
50 | }
51 |
52 | // Service implements the identity service use cases
53 | type Service struct {
54 | Settings *config.Settings
55 | Snapd snapdapi.SnapdClient
56 | }
57 |
58 | // NewService creates a new identity service connection
59 | func NewService(settings *config.Settings, snapd snapdapi.SnapdClient) *Service {
60 | return &Service{
61 | Settings: settings,
62 | Snapd: snapd,
63 | }
64 | }
65 |
66 | // CheckEnrollment verifies that the device is enrolled with the identity service
67 | func (srv *Service) CheckEnrollment() (*domain.Enrollment, error) {
68 | // Get the credentials from the filesystem
69 | en, err := srv.getCredentials()
70 | if err == nil {
71 | return en, nil
72 | }
73 |
74 | // No credentials stored, so enroll the device
75 | // Enroll the device with the identity service
76 | return srv.enrollDevice()
77 | }
78 |
79 | // enroll registers the device with the identity service
80 | func (srv *Service) enrollDevice() (*domain.Enrollment, error) {
81 | // Get the model and serial assertions
82 | data, err := srv.Snapd.GetEncodedAssertions()
83 | if err != nil {
84 | return nil, err
85 | }
86 |
87 | // Format the URL for the identity service
88 | resp, err := sendEnrollmentRequest(srv.Settings.IdentityURL, data)
89 | if err != nil {
90 | return nil, err
91 | }
92 |
93 | // Store the enrollment credentials
94 | err = srv.storeCredentials(resp.Enrollment)
95 | if err != nil {
96 | return nil, err
97 | }
98 |
99 | // Store device data in a separate file
100 | if len(resp.Enrollment.DeviceData) != 0 {
101 | err = storeDeviceData(resp.Enrollment.DeviceData)
102 | if err != nil {
103 | return nil, err
104 | }
105 | }
106 |
107 | return &resp.Enrollment, err
108 | }
109 |
110 | func storeDeviceData(dataBase64 string) error {
111 | data, err := base64.StdEncoding.DecodeString(dataBase64)
112 | if err != nil {
113 | return fmt.Errorf("cannot decode device data: %v", err)
114 | }
115 |
116 | err = ioutil.WriteFile(path.Join(os.Getenv(commonDataEnvVar), deviceDataFileName), data, 0600)
117 | if err != nil {
118 | return fmt.Errorf("cannot write device data: %v", err)
119 | }
120 |
121 | return nil
122 | }
123 |
124 | func sendEnrollmentRequest(idURL string, data []byte) (*web.EnrollResponse, error) {
125 | // Format the URL for the identity service
126 | u, err := url.Parse(idURL)
127 | if err != nil {
128 | return nil, err
129 | }
130 | u.Path = path.Join(u.Path, "v1", "device", "enroll")
131 |
132 | // Send the request to get the credentials from the identity service
133 | resp, err := sendPOSTRequest(u.String(), data)
134 | if err != nil {
135 | return nil, err
136 | }
137 |
138 | if len(resp.StandardResponse.Code) > 0 {
139 | return nil, fmt.Errorf("(%s) %s", resp.StandardResponse.Code, resp.StandardResponse.Message)
140 | }
141 |
142 | return resp, nil
143 | }
144 |
145 | func parseEnrollResponse(r io.Reader) (*web.EnrollResponse, error) {
146 | // Parse the response
147 | result := web.EnrollResponse{}
148 | err := json.NewDecoder(r).Decode(&result)
149 | return &result, err
150 | }
151 |
152 | var sendPOSTRequest = func(u string, data []byte) (*web.EnrollResponse, error) {
153 | // Send the request to get the credentials from the identity service
154 | w, err := http.Post(u, mediaType, bytes.NewReader(data))
155 | if err != nil {
156 | return nil, err
157 | }
158 |
159 | defer w.Body.Close()
160 | return parseEnrollResponse(w.Body)
161 | }
162 |
--------------------------------------------------------------------------------
/identity/identity_test.go:
--------------------------------------------------------------------------------
1 | // -*- Mode: Go; indent-tabs-mode: t -*-
2 |
3 | /*
4 | * This file is part of the IoT Agent
5 | * Copyright 2019 Canonical Ltd.
6 | *
7 | * This program is free software: you can redistribute it and/or modify it
8 | * under the terms of the GNU General Public License version 3, as
9 | * published by the Free Software Foundation.
10 | *
11 | * This program is distributed in the hope that it will be useful, but WITHOUT
12 | * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
13 | * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.
14 | * See the GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | package identity
21 |
22 | import (
23 | "fmt"
24 | "github.com/canonical/iot-agent/snapdapi"
25 | "github.com/canonical/iot-identity/web"
26 | "os"
27 | "strings"
28 | "testing"
29 |
30 | "github.com/canonical/iot-agent/config"
31 | )
32 |
33 | func TestService_CheckEnrollment(t *testing.T) {
34 | settings := config.ReadParameters()
35 | _ = os.Remove(settings.CredentialsPath)
36 | _ = os.Remove("params")
37 | tests := []struct {
38 | name string
39 | sendErr bool
40 | wantErr bool
41 | snapdErr bool
42 | cleanUp bool
43 | withDeviceData bool
44 | }{
45 | {"valid", false, false, false, false, false},
46 | {"valid-secret", false, false, false, true, false},
47 | {"send-error", true, true, false, true, false},
48 | {"snapd-error", false, true, true, true, false},
49 | {"valid-device-data", false, false, false, true, true},
50 | }
51 |
52 | for _, tt := range tests {
53 | t.Run(tt.name, func(t *testing.T) {
54 | if tt.sendErr {
55 | sendPOSTRequest = mockSendRequestError
56 | } else if tt.withDeviceData {
57 | sendPOSTRequest = mockSendDeviceData
58 | } else {
59 | sendPOSTRequest = mockSendRequest
60 | }
61 | snapd := &snapdapi.MockClient{WithError: tt.snapdErr}
62 |
63 | srv := NewService(settings, snapd)
64 | got, err := srv.CheckEnrollment()
65 | if (err != nil) != tt.wantErr {
66 | t.Errorf("Service.CheckEnrollment() error = %v, wantErr %v", err, tt.wantErr)
67 | return
68 | }
69 | if !tt.wantErr {
70 | if got != nil && len(got.ID) == 0 {
71 | t.Error("Service.CheckEnrollment() error = empty enrollment")
72 | }
73 | }
74 |
75 | // Clean up
76 | if tt.cleanUp {
77 | _ = os.Remove(settings.CredentialsPath)
78 | _ = os.Remove("params")
79 | _ = os.Remove("device-data.bin")
80 | }
81 | })
82 | }
83 | }
84 |
85 | func mockSendRequest(u string, data []byte) (*web.EnrollResponse, error) {
86 | const resp = `{"enrollment": {"id":"abc123"}}`
87 |
88 | return parseEnrollResponse(strings.NewReader(resp))
89 | }
90 |
91 | func mockSendDeviceData(u string, data []byte) (*web.EnrollResponse, error) {
92 | // deviceData=encode('Hello base 64 world')
93 | const resp = `{"enrollment": {"id":"abc123","deviceData":"SGVsbG8gYmFzZSA2NCB3b3JsZA=="}}`
94 |
95 | return parseEnrollResponse(strings.NewReader(resp))
96 | }
97 |
98 | func mockSendRequestError(u string, data []byte) (*web.EnrollResponse, error) {
99 | return nil, fmt.Errorf("mock send request error")
100 | }
101 |
--------------------------------------------------------------------------------
/identity/store.go:
--------------------------------------------------------------------------------
1 | // -*- Mode: Go; indent-tabs-mode: t -*-
2 |
3 | /*
4 | * This file is part of the IoT Agent
5 | * Copyright 2019 Canonical Ltd.
6 | *
7 | * This program is free software: you can redistribute it and/or modify it
8 | * under the terms of the GNU General Public License version 3, as
9 | * published by the Free Software Foundation.
10 | *
11 | * This program is distributed in the hope that it will be useful, but WITHOUT
12 | * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
13 | * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.
14 | * See the GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | package identity
21 |
22 | import (
23 | "encoding/json"
24 | "github.com/canonical/iot-identity/domain"
25 | "io/ioutil"
26 | )
27 |
28 | // storeCredentials caches the serialized enrollment details
29 | func (srv *Service) storeCredentials(enroll domain.Enrollment) error {
30 | data, err := json.Marshal(&enroll)
31 | if err != nil {
32 | return nil
33 | }
34 |
35 | return ioutil.WriteFile(srv.Settings.CredentialsPath, data, 0600)
36 | }
37 |
38 | // getCredentials fetches the cached enrollment details
39 | func (srv *Service) getCredentials() (*domain.Enrollment, error) {
40 | enroll := &domain.Enrollment{}
41 |
42 | // Read the credentials from the filesystem
43 | data, err := ioutil.ReadFile(srv.Settings.CredentialsPath)
44 | if err != nil {
45 | return nil, err
46 | }
47 |
48 | // Deserialize the credentials
49 | err = json.Unmarshal(data, enroll)
50 | return enroll, err
51 | }
52 |
--------------------------------------------------------------------------------
/mqtt/metrics.go:
--------------------------------------------------------------------------------
1 | // -*- Mode: Go; indent-tabs-mode: t -*-
2 |
3 | /*
4 | * This file is part of the IoT Agent
5 | * Copyright 2020 Canonical Ltd.
6 | *
7 | * This program is free software: you can redistribute it and/or modify it
8 | * under the terms of the GNU General Public License version 3, as
9 | * published by the Free Software Foundation.
10 | *
11 | * This program is distributed in the hope that it will be useful, but WITHOUT
12 | * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
13 | * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.
14 | * See the GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | package mqtt
21 |
22 | import (
23 | "fmt"
24 | "github.com/shirou/gopsutil/cpu"
25 | "github.com/shirou/gopsutil/mem"
26 | "log"
27 | )
28 |
29 | // Metrics publishes a metrics messages to indicate so the device can be monitored
30 | func (c *Connection) Metrics() {
31 | // Publish the stats
32 | c.memory()
33 | c.cpu()
34 | }
35 |
36 | func (c *Connection) publishMetrics(payload string) {
37 | // The topic to publish the response to the specific action
38 | t := fmt.Sprintf("metrics/%s", c.organisationID)
39 | c.client.Publish(t, QOSAtMostOnce, false, []byte(payload))
40 | }
41 |
42 | func (c *Connection) memory() {
43 | v, err := mem.VirtualMemory()
44 | if err != nil {
45 | log.Printf("Error getting memory usage: %v\n", err)
46 | return
47 | }
48 |
49 | payload := fmt.Sprintf("memory,device=%s total=%d,used=%d,usedpc=%f", c.clientID, v.Total, v.Used, v.UsedPercent)
50 | c.publishMetrics(payload)
51 | }
52 |
53 | func (c *Connection) cpu() {
54 | vv, err := cpu.Times(false)
55 | if err != nil {
56 | log.Printf("Error getting cpu usage: %v\n", err)
57 | return
58 | }
59 |
60 | var user, system, total float64
61 | for _, v := range vv {
62 | user += v.User
63 | system += v.System
64 | total += v.Total()
65 | }
66 |
67 | payload := fmt.Sprintf("cpu,device=%s user=%f,system=%f,total=%f", c.clientID, user, system, total)
68 | c.publishMetrics(payload)
69 | }
70 |
--------------------------------------------------------------------------------
/mqtt/mqtt.go:
--------------------------------------------------------------------------------
1 | // -*- Mode: Go; indent-tabs-mode: t -*-
2 |
3 | /*
4 | * This file is part of the IoT Agent
5 | * Copyright 2019 Canonical Ltd.
6 | *
7 | * This program is free software: you can redistribute it and/or modify it
8 | * under the terms of the GNU General Public License version 3, as
9 | * published by the Free Software Foundation.
10 | *
11 | * This program is distributed in the hope that it will be useful, but WITHOUT
12 | * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
13 | * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.
14 | * See the GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | package mqtt
21 |
22 | import (
23 | "crypto/tls"
24 | "crypto/x509"
25 | "encoding/json"
26 | "fmt"
27 | twin "github.com/canonical/iot-devicetwin/domain"
28 | "github.com/canonical/iot-identity/domain"
29 | MQTT "github.com/eclipse/paho.mqtt.golang"
30 | "log"
31 | "time"
32 | )
33 |
34 | // Constants for connecting to the MQTT broker
35 | const (
36 | quiesce = 250
37 | QOSAtMostOnce = byte(0)
38 | QOSAtLeastOnce = byte(1)
39 | //QOSExactlyOnce = byte(2)
40 | )
41 |
42 | // Connection for MQTT protocol
43 | type Connection struct {
44 | client MQTT.Client
45 | clientID string
46 | organisationID string
47 | }
48 |
49 | var conn *Connection
50 | var client MQTT.Client
51 |
52 | // GetConnection fetches or creates an MQTT connection
53 | func GetConnection(enroll *domain.Enrollment) (*Connection, error) {
54 | if conn == nil {
55 | // Create the client
56 | client, err := newClient(enroll)
57 | if err != nil {
58 | return nil, err
59 | }
60 |
61 | // Create a new connection
62 | conn = &Connection{
63 | client: client,
64 | clientID: enroll.ID,
65 | organisationID: enroll.Organization.ID,
66 | }
67 | }
68 |
69 | // Check that we have a live connection
70 | if conn.client.IsConnectionOpen() {
71 | return conn, nil
72 | }
73 |
74 | // Connect to the MQTT broker
75 | if token := conn.client.Connect(); token.Wait() && token.Error() != nil {
76 | return nil, token.Error()
77 | }
78 |
79 | // Subscribe to the actions topic
80 | err := conn.SubscribeToActions()
81 |
82 | return conn, err
83 | }
84 |
85 | // newClient creates a new MQTT client
86 | func newClient(enroll *domain.Enrollment) (MQTT.Client, error) {
87 | // Return the active client, if we have one
88 | if client != nil {
89 | return client, nil
90 | }
91 |
92 | // Generate a new MQTT client
93 | url := fmt.Sprintf("ssl://%s:%s", enroll.Credentials.MQTTURL, enroll.Credentials.MQTTPort)
94 | log.Println("Connect to the MQTT broker", url)
95 |
96 | // Generate the TLS config from the enrollment credentials
97 | tlsConfig, err := newTLSConfig(enroll)
98 | if err != nil {
99 | return nil, err
100 | }
101 |
102 | // Set up the MQTT client options
103 | opts := MQTT.NewClientOptions()
104 | opts.AddBroker(url)
105 | opts.SetClientID(enroll.ID)
106 | opts.SetTLSConfig(tlsConfig)
107 | opts.AutoReconnect = true
108 | //opts.SetOnConnectHandler(connectHandler)
109 |
110 | client = MQTT.NewClient(opts)
111 | return client, nil
112 | }
113 |
114 | // newTLSConfig sets up the certificates from the enrollment record
115 | func newTLSConfig(enroll *domain.Enrollment) (*tls.Config, error) {
116 | certPool := x509.NewCertPool()
117 | certPool.AppendCertsFromPEM(enroll.Organization.RootCert)
118 |
119 | // Import client certificate/key pair
120 | cert, err := tls.X509KeyPair(enroll.Credentials.Certificate, enroll.Credentials.PrivateKey)
121 | if err != nil {
122 | return nil, err
123 | }
124 |
125 | // Create tls.Config with desired TLS properties
126 | return &tls.Config{
127 | // RootCAs = certs used to verify server cert.
128 | RootCAs: certPool,
129 | // ClientAuth = whether to request cert from server.
130 | // Since the server is set up for SSL, this happens
131 | // anyways.
132 | ClientAuth: tls.NoClientCert,
133 | // ClientCAs = certs used to validate client cert.
134 | ClientCAs: nil,
135 | // InsecureSkipVerify = verify that cert contents
136 | // match server. IP matches what is in cert etc.
137 | InsecureSkipVerify: true,
138 | // Certificates = list of certs client sends to server.
139 | Certificates: []tls.Certificate{cert},
140 | }, nil
141 | }
142 |
143 | // SubscribeToActions subscribes to the action topic
144 | func (c *Connection) SubscribeToActions() error {
145 | t := fmt.Sprintf("devices/sub/%s", c.clientID)
146 | token := c.client.Subscribe(t, QOSAtLeastOnce, c.SubscribeHandler)
147 | token.Wait()
148 | if token.Error() != nil {
149 | log.Printf("Error subscribing to topic `%s`: %v", t, token.Error())
150 | return fmt.Errorf("error subscribing to topic `%s`: %v", t, token.Error())
151 | }
152 | return nil
153 | }
154 |
155 | // SubscribeHandler is the handler for the main subscription topic
156 | func (c *Connection) SubscribeHandler(client MQTT.Client, msg MQTT.Message) {
157 | s, err := deserializePayload(msg)
158 | if err != nil {
159 | return
160 | }
161 |
162 | // The topic to publish the response to the specific action
163 | t := fmt.Sprintf("devices/pub/%s", c.clientID)
164 |
165 | // Perform the action
166 | response, err := c.performAction(s)
167 | if err != nil {
168 | log.Printf("Error with action `%s`: %v", s.Action, err)
169 | }
170 |
171 | // Publish the response to the action to the broker
172 | client.Publish(t, QOSAtLeastOnce, false, response)
173 | }
174 |
175 | // Health publishes a health message to indicate that the device is still active
176 | func (c *Connection) Health() {
177 | // Serialize the device health details
178 | h := twin.Health{
179 | OrganizationID: c.organisationID,
180 | DeviceID: c.clientID,
181 | Refresh: time.Now(),
182 | }
183 | data, err := json.Marshal(&h)
184 | if err != nil {
185 | log.Printf("Error serializing the health data: %v", err)
186 | return
187 | }
188 |
189 | // The topic to publish the response to the specific action
190 | t := fmt.Sprintf("devices/health/%s", c.clientID)
191 | c.client.Publish(t, QOSAtMostOnce, false, data)
192 | }
193 |
194 | // Close closes the connection to the MQTT broker
195 | func (c *Connection) Close() {
196 | c.client.Disconnect(quiesce)
197 | }
198 |
--------------------------------------------------------------------------------
/mqtt/mqtt_test.go:
--------------------------------------------------------------------------------
1 | // -*- Mode: Go; indent-tabs-mode: t -*-
2 |
3 | /*
4 | * This file is part of the IoT Agent
5 | * Copyright 2019 Canonical Ltd.
6 | *
7 | * This program is free software: you can redistribute it and/or modify it
8 | * under the terms of the GNU General Public License version 3, as
9 | * published by the Free Software Foundation.
10 | *
11 | * This program is distributed in the hope that it will be useful, but WITHOUT
12 | * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
13 | * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.
14 | * See the GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | package mqtt
21 |
22 | import (
23 | "encoding/json"
24 | "github.com/canonical/iot-agent/snapdapi"
25 | twin "github.com/canonical/iot-devicetwin/domain"
26 | "github.com/canonical/iot-identity/domain"
27 | MQTT "github.com/eclipse/paho.mqtt.golang"
28 | "log"
29 | "testing"
30 | )
31 |
32 | func TestConnection_Workflow(t *testing.T) {
33 | m1a := `{"id": "abc123", "action":"install", "snap":"helloworld"}`
34 | m1b := `{"id": "abc123", "action":"install"}`
35 | m1c := `{"id": "abc123", "action":"install", "snap":"invalid"}`
36 | m2a := `{"id": "abc123", "action":"invalid", "snap":"helloworld"}`
37 | m2b := `\u1000`
38 | m3a := `{"id": "abc123", "action":"remove", "snap":"helloworld"}`
39 | m3b := `{"id": "abc123", "action":"remove"}`
40 | m3c := `{"id": "abc123", "action":"remove", "snap":"invalid"}`
41 | m4a := `{"id": "abc123", "action":"refresh", "snap":"helloworld"}`
42 | m4b := `{"id": "abc123", "action":"refresh"}`
43 | m4c := `{"id": "abc123", "action":"refresh", "snap":"invalid"}`
44 | m5a := `{"id": "abc123", "action":"revert", "snap":"helloworld"}`
45 | m5b := `{"id": "abc123", "action":"revert"}`
46 | m5c := `{"id": "abc123", "action":"revert", "snap":"invalid"}`
47 | m6a := `{"id": "abc123", "action":"list"}`
48 | m7a := `{"id": "abc123", "action":"enable", "snap":"helloworld"}`
49 | m7b := `{"id": "abc123", "action":"enable"}`
50 | m7c := `{"id": "abc123", "action":"enable", "snap":"invalid"}`
51 | m8a := `{"id": "abc123", "action":"disable", "snap":"helloworld"}`
52 | m8b := `{"id": "abc123", "action":"disable"}`
53 | m8c := `{"id": "abc123", "action":"disable", "snap":"invalid"}`
54 | m9a := `{"id": "abc123", "action":"conf", "snap":"helloworld"}`
55 | m9b := `{"id": "abc123", "action":"conf"}`
56 | m9c := `{"id": "abc123", "action":"conf", "snap":"invalid"}`
57 | m10a := `{"id": "abc123", "action":"setconf", "snap":"helloworld", "data":"{\"title\": \"Hello World!\"}"}`
58 | m10b := `{"id": "abc123", "action":"setconf"}`
59 | m10c := `{"id": "abc123", "action":"setconf", "snap":"invalid", "data":"{\"title\": \"Hello World!\"}"}`
60 | m10d := `{"id": "abc123", "action":"setconf", "snap":"helloworld", "data":"\u1000"}`
61 | m11a := `{"id": "abc123", "action":"info", "snap":"helloworld"}`
62 | m11b := `{"id": "abc123", "action":"info"}`
63 | m11c := `{"id": "abc123", "action":"info", "snap":"invalid"}`
64 | m12a := `{"id": "abc123", "action":"ack", "data":"serialized-assertion"}`
65 | m12b := `{"id": "abc123", "action":"ack", "data":"invalid"}`
66 | m13a := `{"id": "abc123", "action":"server"}`
67 | m14a := `{"id": "abc123", "action":"device"}`
68 |
69 | enroll := &domain.Enrollment{
70 | Credentials: domain.Credentials{
71 | MQTTURL: "localhost",
72 | MQTTPort: "8883",
73 | },
74 | }
75 | client = &MockClient{}
76 | tests := []struct {
77 | name string
78 | open bool
79 | message MQTT.Message
80 | snapdErr bool
81 | withErr bool
82 | respErr bool
83 | }{
84 | {"valid-closed", false, &MockMessage{[]byte(m1a)}, false, false, false},
85 | {"valid-open", true, &MockMessage{[]byte(m1a)}, false, false, false},
86 | {"no-snap", true, &MockMessage{[]byte(m1b)}, false, false, true},
87 | {"invalid-install", true, &MockMessage{[]byte(m1c)}, false, false, true},
88 |
89 | {"invalid-action", true, &MockMessage{[]byte(m2a)}, false, true, true},
90 | {"bad-data", true, &MockMessage{[]byte(m2b)}, false, true, true},
91 |
92 | {"valid-remove", true, &MockMessage{[]byte(m3a)}, false, false, false},
93 | {"no-snap-remove", true, &MockMessage{[]byte(m3b)}, false, false, true},
94 | {"invalid-remove", true, &MockMessage{[]byte(m3c)}, false, false, true},
95 |
96 | {"valid-refresh", true, &MockMessage{[]byte(m4a)}, false, false, false},
97 | {"no-snap-refresh", true, &MockMessage{[]byte(m4b)}, false, false, true},
98 | {"invalid-refresh", true, &MockMessage{[]byte(m4c)}, false, false, true},
99 |
100 | {"valid-revert", true, &MockMessage{[]byte(m5a)}, false, false, false},
101 | {"no-snap-revert", true, &MockMessage{[]byte(m5b)}, false, false, true},
102 | {"invalid-revert", true, &MockMessage{[]byte(m5c)}, false, false, true},
103 |
104 | {"valid-list", true, &MockMessage{[]byte(m6a)}, false, false, false},
105 | {"snapd-error-list", true, &MockMessage{[]byte(m6a)}, true, false, true},
106 |
107 | {"valid-enable", true, &MockMessage{[]byte(m7a)}, false, false, false},
108 | {"no-snap-enable", true, &MockMessage{[]byte(m7b)}, false, false, true},
109 | {"invalid-enable", true, &MockMessage{[]byte(m7c)}, false, false, true},
110 |
111 | {"valid-disable", true, &MockMessage{[]byte(m8a)}, false, false, false},
112 | {"no-snap-disable", true, &MockMessage{[]byte(m8b)}, false, false, true},
113 | {"invalid-disable", true, &MockMessage{[]byte(m8c)}, false, false, true},
114 |
115 | {"valid-conf", true, &MockMessage{[]byte(m9a)}, false, false, false},
116 | {"no-snap-conf", true, &MockMessage{[]byte(m9b)}, false, false, true},
117 | {"invalid-conf", true, &MockMessage{[]byte(m9c)}, false, false, true},
118 |
119 | {"valid-setconf", true, &MockMessage{[]byte(m10a)}, false, false, false},
120 | {"no-snap-setconf", true, &MockMessage{[]byte(m10b)}, false, false, true},
121 | {"invalid-setconf", true, &MockMessage{[]byte(m10c)}, false, false, true},
122 | {"bad-data-setconf", true, &MockMessage{[]byte(m10d)}, false, false, true},
123 |
124 | {"valid-info", false, &MockMessage{[]byte(m11a)}, false, false, false},
125 | {"no-snap-info", true, &MockMessage{[]byte(m11b)}, false, false, true},
126 | {"invalid-info", true, &MockMessage{[]byte(m11c)}, false, false, true},
127 |
128 | {"valid-ack", false, &MockMessage{[]byte(m12a)}, false, false, false},
129 | {"invalid-ack", false, &MockMessage{[]byte(m12b)}, false, false, true},
130 |
131 | {"valid-server", false, &MockMessage{[]byte(m13a)}, false, false, false},
132 | {"snapd-error-server", false, &MockMessage{[]byte(m13a)}, true, false, true},
133 |
134 | {"valid-deviceinfo", false, &MockMessage{[]byte(m14a)}, false, false, false},
135 | {"snapd-error-deviceinfo", false, &MockMessage{[]byte(m14a)}, true, false, true},
136 | }
137 | for _, tt := range tests {
138 | t.Run(tt.name, func(t *testing.T) {
139 | snapd = &snapdapi.MockClient{WithError: tt.snapdErr}
140 | if tt.open {
141 | client.Connect()
142 | }
143 | c, err := GetConnection(enroll)
144 | if err != nil {
145 | t.Error("TestConnection_Workflow: error creating connection")
146 | return
147 | }
148 | if c.client == nil {
149 | t.Error("TestConnection_Workflow: no client created")
150 | }
151 |
152 | // Publish the health
153 | c.Health()
154 |
155 | // Subscribe action
156 | c.SubscribeHandler(client, tt.message)
157 |
158 | // Check again with the action
159 | sa, err := deserializePayload(tt.message)
160 | if err != nil && !tt.withErr {
161 | t.Error("TestConnection_Workflow: payload - expected error got none")
162 | return
163 | }
164 | resp, err := c.performAction(sa)
165 | if err != nil && !tt.withErr {
166 | t.Error("TestConnection_Workflow: action - expected error got none")
167 | return
168 | }
169 |
170 | r, err := deserializePublishResponse(resp)
171 | if err != nil && !tt.withErr {
172 | t.Errorf("TestConnection_Workflow: publish response: %v", err)
173 | return
174 | }
175 | if r == nil {
176 | t.Error("TestConnection_Workflow: publish response is nil")
177 | return
178 | }
179 | if r.Success == tt.respErr {
180 | t.Errorf("TestConnection_Workflow: publish response unexpected: %s", r.Message)
181 | }
182 | })
183 | }
184 | }
185 |
186 | func deserializePublishResponse(data []byte) (*twin.PublishResponse, error) {
187 | s := twin.PublishResponse{}
188 |
189 | // Decode the message payload - the list of snaps
190 | err := json.Unmarshal(data, &s)
191 | if err != nil {
192 | log.Println("Error decoding the published message:", err)
193 | }
194 | return &s, err
195 | }
196 |
--------------------------------------------------------------------------------
/mqtt/subscribe.go:
--------------------------------------------------------------------------------
1 | // -*- Mode: Go; indent-tabs-mode: t -*-
2 |
3 | /*
4 | * This file is part of the IoT Agent
5 | * Copyright 2019 Canonical Ltd.
6 | *
7 | * This program is free software: you can redistribute it and/or modify it
8 | * under the terms of the GNU General Public License version 3, as
9 | * published by the Free Software Foundation.
10 | *
11 | * This program is distributed in the hope that it will be useful, but WITHOUT
12 | * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
13 | * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.
14 | * See the GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | package mqtt
21 |
22 | import (
23 | "encoding/json"
24 | "fmt"
25 | "github.com/canonical/iot-devicetwin/domain"
26 | MQTT "github.com/eclipse/paho.mqtt.golang"
27 | "log"
28 | )
29 |
30 | // performAction acts on the topic and returns a response to publish back
31 | func (c *Connection) performAction(s *SubscribeAction) ([]byte, error) {
32 | var result domain.PublishResponse
33 | // Act based on the message action
34 | switch s.Action {
35 | case "device":
36 | result = s.Device(c.organisationID, c.clientID)
37 | case "list":
38 | result = s.SnapList(c.clientID)
39 | case "install":
40 | result = s.SnapInstall()
41 | case "remove":
42 | result = s.SnapRemove()
43 | case "refresh":
44 | result = s.SnapRefresh()
45 | case "revert":
46 | result = s.SnapRevert()
47 | case "enable":
48 | result = s.SnapEnable()
49 | case "disable":
50 | result = s.SnapDisable()
51 | case "conf":
52 | result = s.SnapConf()
53 | case "setconf":
54 | result = s.SnapSetConf()
55 | case "info":
56 | result = s.SnapInfo()
57 | case "ack":
58 | result = s.SnapAck()
59 | case "server":
60 | result = s.SnapServerVersion(c.clientID)
61 |
62 | default:
63 | return nil, fmt.Errorf("unhandled action: %s", s.Action)
64 | }
65 |
66 | result.Action = s.Action
67 | return serializeResponse(result)
68 | }
69 |
70 | func deserializePayload(msg MQTT.Message) (*SubscribeAction, error) {
71 | s := SubscribeAction{}
72 |
73 | // Decode the message payload - the list of snaps
74 | err := json.Unmarshal(msg.Payload(), &s)
75 | if err != nil {
76 | log.Println("Error decoding the subscribed message:", err)
77 | }
78 | return &s, err
79 | }
80 |
81 | func serializeResponse(resp interface{}) ([]byte, error) {
82 | return json.Marshal(resp)
83 | }
84 |
--------------------------------------------------------------------------------
/mqtt/subscribe_action.go:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the IoT Agent
3 | * Copyright 2019 Canonical Ltd.
4 | *
5 | * This program is free software: you can redistribute it and/or modify it
6 | * under the terms of the GNU General Public License version 3, as
7 | * published by the Free Software Foundation.
8 | *
9 | * This program is distributed in the hope that it will be useful, but WITHOUT
10 | * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
11 | * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.
12 | * See the GNU General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package mqtt
19 |
20 | import (
21 | "encoding/json"
22 | "github.com/canonical/iot-agent/snapdapi"
23 | "github.com/canonical/iot-devicetwin/domain"
24 | )
25 |
26 | // SubscribeAction is the message format for the action topic
27 | type SubscribeAction struct {
28 | ID string `json:"id"`
29 | Action string `json:"action"`
30 | Snap string `json:"snap"`
31 | Data string `json:"data"`
32 | }
33 |
34 | var snapd snapdapi.SnapdClient = snapdapi.NewClientAdapter()
35 |
36 | // Device gets details of the device
37 | func (act *SubscribeAction) Device(orgID, deviceID string) domain.PublishResponse {
38 | // Call the snapd API for the device information
39 | info, err := snapd.DeviceInfo()
40 | if err != nil {
41 | return domain.PublishResponse{ID: act.ID, Success: false, Message: err.Error()}
42 | }
43 |
44 | result := domain.Device{
45 | OrganizationID: orgID,
46 | DeviceID: deviceID,
47 | Brand: info.Brand,
48 | Model: info.Model,
49 | SerialNumber: info.SerialNumber,
50 | DeviceKey: info.DeviceKey,
51 | StoreID: info.StoreID,
52 | }
53 |
54 | // Call the snapd API for the OS version information (ignore errors)
55 | version, err := act.serverVersion(deviceID)
56 | if err == nil {
57 | result.Version = version
58 | }
59 |
60 | return domain.PublishResponse{ID: act.ID, Success: true, Result: result}
61 | }
62 |
63 | // SnapInstall installs a new snap
64 | func (act *SubscribeAction) SnapInstall() domain.PublishResponse {
65 | if len(act.Snap) == 0 {
66 | return domain.PublishResponse{ID: act.ID, Success: false, Message: "No snap name provided for install"}
67 | }
68 |
69 | // Call the snapd API
70 | result, err := snapd.Install(act.Snap, nil)
71 | if err != nil {
72 | return domain.PublishResponse{ID: act.ID, Success: false, Message: err.Error()}
73 | }
74 | return domain.PublishResponse{ID: act.ID, Success: true, Result: result}
75 | }
76 |
77 | // SnapRemove removes an existing snap
78 | func (act *SubscribeAction) SnapRemove() domain.PublishResponse {
79 | if len(act.Snap) == 0 {
80 | return domain.PublishResponse{ID: act.ID, Success: false, Message: "No snap name provided for remove"}
81 | }
82 |
83 | // Call the snapd API
84 | result, err := snapd.Remove(act.Snap, nil)
85 | if err != nil {
86 | return domain.PublishResponse{ID: act.ID, Success: false, Message: err.Error()}
87 | }
88 | return domain.PublishResponse{ID: act.ID, Success: true, Result: result}
89 | }
90 |
91 | // SnapList lists installed snaps
92 | func (act *SubscribeAction) SnapList(deviceID string) domain.PublishResponse {
93 | // Call the snapd API
94 | snaps, err := snapd.List([]string{}, nil)
95 | if err != nil {
96 | return domain.PublishResponse{ID: act.ID, Success: false, Message: err.Error()}
97 | }
98 |
99 | // Convert the snaps into the device twin format
100 | ss := []domain.DeviceSnap{}
101 |
102 | for _, s := range snaps {
103 | // Get the config for the snap (ignore errors)
104 | var conf string
105 | c, err := snapd.Conf(s.Name)
106 | if err == nil {
107 | resp, err := serializeResponse(c)
108 | if err == nil {
109 | conf = string(resp)
110 | }
111 | }
112 |
113 | ss = append(ss, domain.DeviceSnap{
114 | DeviceID: deviceID,
115 | Name: s.Name,
116 | InstalledSize: s.InstalledSize,
117 | InstalledDate: s.InstallDate,
118 | Status: s.Status,
119 | Channel: s.Channel,
120 | Confinement: s.Confinement,
121 | Version: s.Version,
122 | Revision: s.Revision.N,
123 | Devmode: s.DevMode,
124 | Config: conf,
125 | })
126 | }
127 |
128 | return domain.PublishResponse{ID: act.ID, Success: true, Result: ss}
129 | }
130 |
131 | // SnapRefresh refreshes an existing snap
132 | func (act *SubscribeAction) SnapRefresh() domain.PublishResponse {
133 | if len(act.Snap) == 0 {
134 | return domain.PublishResponse{ID: act.ID, Success: false, Message: "No snap name provided for refresh"}
135 | }
136 |
137 | // Call the snapd API
138 | result, err := snapd.Refresh(act.Snap, nil)
139 | if err != nil {
140 | return domain.PublishResponse{ID: act.ID, Success: false, Message: err.Error()}
141 | }
142 | return domain.PublishResponse{ID: act.ID, Success: true, Result: result}
143 | }
144 |
145 | // SnapRevert reverts an existing snap
146 | func (act *SubscribeAction) SnapRevert() domain.PublishResponse {
147 | if len(act.Snap) == 0 {
148 | return domain.PublishResponse{ID: act.ID, Success: false, Message: "No snap name provided for revert"}
149 | }
150 |
151 | // Call the snapd API
152 | result, err := snapd.Revert(act.Snap, nil)
153 | if err != nil {
154 | return domain.PublishResponse{ID: act.ID, Success: false, Message: err.Error()}
155 | }
156 | return domain.PublishResponse{ID: act.ID, Success: true, Result: result}
157 | }
158 |
159 | // SnapEnable enables an existing snap
160 | func (act *SubscribeAction) SnapEnable() domain.PublishResponse {
161 | if len(act.Snap) == 0 {
162 | return domain.PublishResponse{ID: act.ID, Success: false, Message: "No snap name provided for enable"}
163 | }
164 |
165 | // Call the snapd API
166 | result, err := snapd.Enable(act.Snap, nil)
167 | if err != nil {
168 | return domain.PublishResponse{ID: act.ID, Success: false, Message: err.Error()}
169 | }
170 | return domain.PublishResponse{ID: act.ID, Success: true, Result: result}
171 | }
172 |
173 | // SnapDisable disables an existing snap
174 | func (act *SubscribeAction) SnapDisable() domain.PublishResponse {
175 | if len(act.Snap) == 0 {
176 | return domain.PublishResponse{ID: act.ID, Success: false, Message: "No snap name provided for disable"}
177 | }
178 |
179 | // Call the snapd API
180 | result, err := snapd.Disable(act.Snap, nil)
181 | if err != nil {
182 | return domain.PublishResponse{ID: act.ID, Success: false, Message: err.Error()}
183 | }
184 | return domain.PublishResponse{ID: act.ID, Success: true, Result: result}
185 | }
186 |
187 | // SnapConf gets the config for a snap
188 | func (act *SubscribeAction) SnapConf() domain.PublishResponse {
189 | if len(act.Snap) == 0 {
190 | return domain.PublishResponse{ID: act.ID, Success: false, Message: "No snap name provided for config"}
191 | }
192 |
193 | // Call the snapd API
194 | result, err := snapd.Conf(act.Snap)
195 | if err != nil {
196 | return domain.PublishResponse{ID: act.ID, Success: false, Message: err.Error()}
197 | }
198 |
199 | return domain.PublishResponse{ID: act.ID, Success: true, Result: result}
200 | }
201 |
202 | // SnapSetConf sets the config for a snap
203 | func (act *SubscribeAction) SnapSetConf() domain.PublishResponse {
204 | if len(act.Snap) == 0 {
205 | return domain.PublishResponse{ID: act.ID, Success: false, Message: "No snap name provided for set config"}
206 | }
207 |
208 | // Deserialize the settings
209 | var data map[string]interface{}
210 | if err := json.Unmarshal([]byte(act.Data), &data); err != nil {
211 | return domain.PublishResponse{ID: act.ID, Success: false, Message: err.Error()}
212 | }
213 |
214 | // Call the snapd API
215 | result, err := snapd.SetConf(act.Snap, data)
216 | if err != nil {
217 | return domain.PublishResponse{ID: act.ID, Success: false, Message: err.Error()}
218 | }
219 |
220 | return domain.PublishResponse{ID: act.ID, Success: true, Result: result}
221 | }
222 |
223 | // SnapInfo gets the info for a snap
224 | func (act *SubscribeAction) SnapInfo() domain.PublishResponse {
225 | if len(act.Snap) == 0 {
226 | return domain.PublishResponse{ID: act.ID, Success: false, Message: "No snap name provided for snap info"}
227 | }
228 |
229 | // Call the snapd API
230 | result, _, err := snapd.Snap(act.Snap)
231 | if err != nil {
232 | return domain.PublishResponse{ID: act.ID, Success: false, Message: err.Error()}
233 | }
234 |
235 | return domain.PublishResponse{ID: act.ID, Success: true, Result: result}
236 | }
237 |
238 | // SnapAck adds an assertion to the device
239 | func (act *SubscribeAction) SnapAck() domain.PublishResponse {
240 | // Call the snapd API
241 | err := snapd.Ack([]byte(act.Data))
242 | if err != nil {
243 | return domain.PublishResponse{ID: act.ID, Success: false, Message: err.Error()}
244 | }
245 |
246 | return domain.PublishResponse{ID: act.ID, Success: true}
247 | }
248 |
249 | // SnapServerVersion gets details of the device
250 | func (act *SubscribeAction) SnapServerVersion(deviceID string) domain.PublishResponse {
251 | // Call the snapd API
252 | result, err := act.serverVersion(deviceID)
253 | if err != nil {
254 | return domain.PublishResponse{ID: act.ID, Success: false, Message: err.Error()}
255 | }
256 |
257 | return domain.PublishResponse{ID: act.ID, Success: true, Result: result}
258 | }
259 |
260 | func (act *SubscribeAction) serverVersion(deviceID string) (domain.DeviceVersion, error) {
261 | // Call the snapd API
262 | version, err := snapd.ServerVersion()
263 | if err != nil {
264 | return domain.DeviceVersion{}, err
265 | }
266 |
267 | return domain.DeviceVersion{
268 | DeviceID: deviceID,
269 | Version: version.Version,
270 | Series: version.Series,
271 | OSID: version.OSID,
272 | OSVersionID: version.OSVersionID,
273 | OnClassic: version.OnClassic,
274 | KernelVersion: version.KernelVersion,
275 | }, nil
276 | }
277 |
--------------------------------------------------------------------------------
/mqtt/testing_client.go:
--------------------------------------------------------------------------------
1 | // -*- Mode: Go; indent-tabs-mode: t -*-
2 |
3 | /*
4 | * This file is part of the IoT Agent
5 | * Copyright 2019 Canonical Ltd.
6 | *
7 | * This program is free software: you can redistribute it and/or modify it
8 | * under the terms of the GNU General Public License version 3, as
9 | * published by the Free Software Foundation.
10 | *
11 | * This program is distributed in the hope that it will be useful, but WITHOUT
12 | * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
13 | * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.
14 | * See the GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | package mqtt
21 |
22 | import (
23 | MQTT "github.com/eclipse/paho.mqtt.golang"
24 | "time"
25 | )
26 |
27 | // MockClient mocks the MQTT client
28 | type MockClient struct {
29 | open bool
30 | }
31 |
32 | // IsConnected mocks the connect status
33 | func (cli *MockClient) IsConnected() bool {
34 | return cli.open
35 | }
36 |
37 | // IsConnectionOpen mocks the connect status
38 | func (cli *MockClient) IsConnectionOpen() bool {
39 | return cli.open
40 | }
41 |
42 | // Connect mocks connecting to broker
43 | func (cli *MockClient) Connect() MQTT.Token {
44 | cli.open = true
45 | return &MockToken{}
46 | }
47 |
48 | // Disconnect mocks client close
49 | func (cli *MockClient) Disconnect(quiesce uint) {
50 | cli.open = false
51 | return
52 | }
53 |
54 | // Publish mocks a publish message
55 | func (cli *MockClient) Publish(topic string, qos byte, retained bool, payload interface{}) MQTT.Token {
56 | return &MockToken{}
57 | }
58 |
59 | // Subscribe mocks a subscribe message
60 | func (cli *MockClient) Subscribe(topic string, qos byte, callback MQTT.MessageHandler) MQTT.Token {
61 | return &MockToken{}
62 | }
63 |
64 | // SubscribeMultiple mocks subscribe messages
65 | func (cli *MockClient) SubscribeMultiple(filters map[string]byte, callback MQTT.MessageHandler) MQTT.Token {
66 | return &MockToken{}
67 | }
68 |
69 | // Unsubscribe mocks a unsubscribe message
70 | func (cli *MockClient) Unsubscribe(topics ...string) MQTT.Token {
71 | return &MockToken{}
72 | }
73 |
74 | // AddRoute mocks routing
75 | func (cli *MockClient) AddRoute(topic string, callback MQTT.MessageHandler) {
76 | return
77 | }
78 |
79 | // OptionsReader mocks the options reader (badly)
80 | func (cli *MockClient) OptionsReader() MQTT.ClientOptionsReader {
81 | return MQTT.NewClient(nil).OptionsReader()
82 | }
83 |
84 | // MockToken implements a Token
85 | type MockToken struct{}
86 |
87 | // Wait mocks the token wait
88 | func (t *MockToken) Wait() bool {
89 | return true
90 | }
91 |
92 | // WaitTimeout mocks the token wait timeout
93 | func (t *MockToken) WaitTimeout(time.Duration) bool {
94 | return true
95 | }
96 |
97 | // Error mocks a token error check
98 | func (t *MockToken) Error() error {
99 | return nil
100 | }
101 |
102 | // MockMessage implements an MQTT message
103 | type MockMessage struct {
104 | message []byte
105 | }
106 |
107 | // Duplicate mocks a duplicate message check
108 | func (m *MockMessage) Duplicate() bool {
109 | panic("implement me")
110 | }
111 |
112 | // Qos mocks the QoS flag
113 | func (m *MockMessage) Qos() byte {
114 | panic("implement me")
115 | }
116 |
117 | // Retained mocks the retained flag
118 | func (m *MockMessage) Retained() bool {
119 | panic("implement me")
120 | }
121 |
122 | // Topic mocks the topic
123 | func (m *MockMessage) Topic() string {
124 | panic("implement me")
125 | }
126 |
127 | // MessageID mocks the message ID
128 | func (m *MockMessage) MessageID() uint16 {
129 | return 1000
130 | }
131 |
132 | // Payload mocks the payload retrieval
133 | func (m *MockMessage) Payload() []byte {
134 | return m.message
135 | }
136 |
137 | // Ack mocks the message ack
138 | func (m *MockMessage) Ack() {
139 | panic("implement me")
140 | }
141 |
--------------------------------------------------------------------------------
/run-checks:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | if [ "$TRAVIS_BUILD_NUMBER" ]; then
4 | echo travis_fold:start:env
5 | printenv | sort
6 | echo travis_fold:end:env
7 | fi
8 |
9 | export LANG=C.UTF-8
10 | export LANGUAGE=en
11 | set -eu
12 |
13 | export GO111MODULE=on
14 |
15 | if which goctest >/dev/null; then
16 | goctest="goctest"
17 | else
18 | goctest="go test"
19 | fi
20 | COVERMODE=${COVERMODE:-atomic}
21 | export GOPATH="${GOPATH:-$(realpath "$(dirname "$0")"/../../../../)}"
22 | export PATH="$PATH:${GOPATH%%:*}/bin"
23 |
24 | STATIC=
25 | UNIT=
26 |
27 | case "${1:-all}" in
28 | all)
29 | STATIC=1
30 | UNIT=1
31 | ;;
32 | --static)
33 | STATIC=1
34 | ;;
35 | --unit)
36 | UNIT=1
37 | ;;
38 | *)
39 | echo "Wrong flag ${1}. To run a single suite use --static or --unit"
40 | exit 1
41 | esac
42 |
43 | CURRENTTRAP="true"
44 | EXIT_CODE=99
45 | store_exit_code() {
46 | EXIT_CODE=$?
47 | }
48 | exit_with_exit_code() {
49 | exit $EXIT_CODE
50 | }
51 | addtrap() {
52 | CURRENTTRAP="$CURRENTTRAP ; $1"
53 | trap "store_exit_code; $CURRENTTRAP ; exit_with_exit_code" EXIT
54 | }
55 |
56 | endmsg() {
57 | if [ $EXIT_CODE -eq 0 ]; then
58 | p="success.txt"
59 | m="All good, what could possibly go wrong."
60 | else
61 | p="failure.txt"
62 | m="Crushing failure and despair."
63 | fi
64 | echo "$m"
65 | }
66 | addtrap endmsg
67 |
68 | # Append the coverage profile of a package to the project coverage.
69 | append_coverage() {
70 | local profile="$1"
71 | if [ -f $profile ]; then
72 | cat $profile | grep -v "mode: set" >> .coverage/coverage.out
73 | rm $profile
74 | fi
75 | }
76 |
77 |
78 | if [ "$STATIC" = 1 ]; then
79 |
80 | echo Checking formatting
81 | fmt=""
82 | for dir in $(go list -f '{{.Dir}}' ./... ); do
83 | s="$(gofmt -s -l "$dir")"
84 | if [ -n "$s" ]; then
85 | fmt="$s\n$fmt"
86 | fi
87 | done
88 |
89 | if [ -n "$fmt" ]; then
90 | echo "Formatting wrong in following files:"
91 | echo "$fmt"
92 | exit 1
93 | fi
94 |
95 |
96 | # golint
97 | echo Install golint
98 | if ! which golint >/dev/null; then
99 | go get golang.org/x/lint/golint
100 | fi
101 |
102 | echo Running lint
103 | for dir in $(go list -f '{{.Dir}}' ./... ); do
104 | lint="$(golint "$dir")"
105 | if [ -n "$lint" ]; then
106 | echo "Lint complains:"
107 | echo "$lint"
108 | exit 1
109 | fi
110 | done
111 |
112 | echo Checking spelling errors
113 | if ! which misspell >/dev/null; then
114 | go get -u github.com/client9/misspell/cmd/misspell
115 | fi
116 | for file in *; do
117 | if [ "$file" = "static" ] || [ "$file" = "webapp-admin" ] || [ "$file" = "webapp-user" ] || [ "$file" = "test" ]; then
118 | continue
119 | fi
120 | misspell -error -i auther,PROCES,PROCESSS,proces,processs,exportfs "$file"
121 | done
122 |
123 | echo Checking for ineffective assignments
124 | if ! which ineffassign >/dev/null; then
125 | go get -u github.com/gordonklaus/ineffassign
126 | fi
127 | # ineffassign knows about ignoring vendor/ \o/
128 | ineffassign ./...
129 |
130 | echo Checking for naked returns
131 | if ! which nakedret >/dev/null; then
132 | go get -u github.com/alexkohler/nakedret
133 | fi
134 | got=$(nakedret ./... 2>&1)
135 | if [ -n "$got" ]; then
136 | echo "$got"
137 | exit 1
138 | fi
139 | fi
140 |
141 | if [ ! -z "$UNIT" ]; then
142 |
143 | # Prepare the coverage output profile.
144 | rm -rf .coverage
145 | mkdir .coverage
146 | echo "mode: $COVERMODE" > .coverage/coverage.out
147 |
148 | echo Building
149 | go build -v github.com/canonical/iot-agent/...
150 |
151 | # tests
152 | echo Running tests from "$PWD"
153 | for pkg in $(go list ./...); do
154 | go test -i "$pkg"
155 | $goctest -v -coverprofile=.coverage/profile.out -covermode="$COVERMODE" "$pkg"
156 | append_coverage .coverage/profile.out
157 | done
158 |
159 | # upload to codecov.io if on travis
160 | if [ "${TRAVIS_BUILD_NUMBER:-}" ]; then
161 | curl -s https://codecov.io/bash | bash /dev/stdin -f .coverage/coverage.out
162 | fi
163 | fi
164 |
165 | UNCLEAN="$(git status -s|grep ^??)" || true
166 | if [ -n "$UNCLEAN" ]; then
167 | cat <.
18 | */
19 |
20 | package snapdapi
21 |
22 | import (
23 | "log"
24 |
25 | "github.com/snapcore/snapd/asserts"
26 | )
27 |
28 | // ActionDevice has basic information of a device
29 | type ActionDevice struct {
30 | Brand string `json:"brand"`
31 | Model string `json:"model"`
32 | SerialNumber string `json:"serial"`
33 | StoreID string `json:"store"`
34 | DeviceKey string `json:"deviceKey"`
35 | }
36 |
37 | // GetEncodedAssertions fetches the encoded model and serial assertions
38 | func (a *ClientAdapter) GetEncodedAssertions() ([]byte, error) {
39 | // Get the model assertion
40 | modelAssertions, err := a.Known(asserts.ModelType.Name, map[string]string{})
41 | if err != nil || len(modelAssertions) == 0 {
42 | log.Printf("error retrieving the model assertion: %v", err)
43 | return nil, err
44 | }
45 | dataModel := asserts.Encode(modelAssertions[0])
46 |
47 | // Get the serial assertion
48 | serialAssertions, err := a.Known(asserts.SerialType.Name, map[string]string{})
49 | if err != nil || len(serialAssertions) == 0 {
50 | log.Printf("error retrieving the serial assertion: %v", err)
51 | return nil, err
52 | }
53 | dataSerial := asserts.Encode(serialAssertions[0])
54 |
55 | // Bring the assertions together
56 | data := append(dataModel, []byte("\n")...)
57 | data = append(data, dataSerial...)
58 | return data, nil
59 | }
60 |
61 | // DeviceInfo fetches the basic details of the device
62 | func (a *ClientAdapter) DeviceInfo() (ActionDevice, error) {
63 | // Get the model assertion
64 | modelAssertions, err := a.Known(asserts.ModelType.Name, map[string]string{})
65 | if err != nil || len(modelAssertions) == 0 {
66 | log.Printf("error retrieving the model assertion: %v", err)
67 | return ActionDevice{}, err
68 | }
69 | model := modelAssertions[0]
70 |
71 | // Get the serial assertion
72 | serialAssertions, err := a.Known(asserts.SerialType.Name, map[string]string{})
73 | if err != nil || len(serialAssertions) == 0 {
74 | log.Printf("error retrieving the serial assertion: %v", err)
75 | return ActionDevice{}, err
76 | }
77 | serial := serialAssertions[0]
78 |
79 | return ActionDevice{
80 | Brand: serial.HeaderString("brand-id"),
81 | Model: serial.HeaderString("model"),
82 | SerialNumber: serial.HeaderString("serial"),
83 | DeviceKey: serial.HeaderString("device-key"),
84 | StoreID: model.HeaderString("store"),
85 | }, nil
86 | }
87 |
--------------------------------------------------------------------------------
/snapdapi/client.go:
--------------------------------------------------------------------------------
1 | // -*- Mode: Go; indent-tabs-mode: t -*-
2 |
3 | /*
4 | * This file is part of the IoT Agent
5 | * Copyright 2019 Canonical Ltd.
6 | *
7 | * This program is free software: you can redistribute it and/or modify it
8 | * under the terms of the GNU General Public License version 3, as
9 | * published by the Free Software Foundation.
10 | *
11 | * This program is distributed in the hope that it will be useful, but WITHOUT
12 | * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
13 | * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.
14 | * See the GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | package snapdapi
21 |
22 | import (
23 | "sync"
24 |
25 | "github.com/snapcore/snapd/asserts"
26 | "github.com/snapcore/snapd/client"
27 | )
28 |
29 | // SnapdClient is a client of the snapd REST API
30 | type SnapdClient interface {
31 | Snap(name string) (*client.Snap, *client.ResultInfo, error)
32 | List(names []string, opts *client.ListOptions) ([]*client.Snap, error)
33 | Install(name string, options *client.SnapOptions) (string, error)
34 | Refresh(name string, options *client.SnapOptions) (string, error)
35 | Revert(name string, options *client.SnapOptions) (string, error)
36 | Remove(name string, options *client.SnapOptions) (string, error)
37 | Enable(name string, options *client.SnapOptions) (string, error)
38 | Disable(name string, options *client.SnapOptions) (string, error)
39 | ServerVersion() (*client.ServerVersion, error)
40 | Ack(b []byte) error
41 | Known(assertTypeName string, headers map[string]string) ([]asserts.Assertion, error)
42 | Conf(name string) (map[string]interface{}, error)
43 | SetConf(name string, patch map[string]interface{}) (string, error)
44 |
45 | GetEncodedAssertions() ([]byte, error)
46 | DeviceInfo() (ActionDevice, error)
47 | }
48 |
49 | var clientOnce sync.Once
50 | var clientInstance *ClientAdapter
51 |
52 | // ClientAdapter adapts our expectations to the snapd client API.
53 | type ClientAdapter struct {
54 | snapdClient *client.Client
55 | }
56 |
57 | // NewClientAdapter creates a new ClientAdapter as a singleton
58 | func NewClientAdapter() *ClientAdapter {
59 | clientOnce.Do(func() {
60 | clientInstance = &ClientAdapter{
61 | snapdClient: client.New(nil),
62 | }
63 | })
64 |
65 | return clientInstance
66 | }
67 |
68 | // Snap returns the most recently published revision of the snap with the
69 | // provided name.
70 | func (a *ClientAdapter) Snap(name string) (*client.Snap, *client.ResultInfo, error) {
71 | return a.snapdClient.Snap(name)
72 | }
73 |
74 | // List returns the list of all snaps installed on the system
75 | // with names in the given list; if the list is empty, all snaps.
76 | func (a *ClientAdapter) List(names []string, opts *client.ListOptions) ([]*client.Snap, error) {
77 | return a.snapdClient.List(names, opts)
78 | }
79 |
80 | // Install adds the snap with the given name from the given channel (or
81 | // the system default channel if not).
82 | func (a *ClientAdapter) Install(name string, options *client.SnapOptions) (string, error) {
83 | return a.snapdClient.Install(name, options)
84 | }
85 |
86 | // Refresh updates the snap with the given name from the given channel (or
87 | // the system default channel if not).
88 | func (a *ClientAdapter) Refresh(name string, options *client.SnapOptions) (string, error) {
89 | return a.snapdClient.Refresh(name, options)
90 | }
91 |
92 | // Revert rolls the snap back to the previous on-disk state
93 | func (a *ClientAdapter) Revert(name string, options *client.SnapOptions) (string, error) {
94 | return a.snapdClient.Revert(name, options)
95 | }
96 |
97 | // Remove removes the snap with the given name.
98 | func (a *ClientAdapter) Remove(name string, options *client.SnapOptions) (string, error) {
99 | return a.snapdClient.Remove(name, options)
100 | }
101 |
102 | // Enable activates the snap with the given name.
103 | func (a *ClientAdapter) Enable(name string, options *client.SnapOptions) (string, error) {
104 | return a.snapdClient.Enable(name, options)
105 | }
106 |
107 | // Disable deactivates the snap with the given name.
108 | func (a *ClientAdapter) Disable(name string, options *client.SnapOptions) (string, error) {
109 | return a.snapdClient.Disable(name, options)
110 | }
111 |
112 | // ServerVersion returns information about the snapd server.
113 | func (a *ClientAdapter) ServerVersion() (*client.ServerVersion, error) {
114 | return a.snapdClient.ServerVersion()
115 | }
116 |
117 | // Ack adds a new assertion to the system
118 | func (a *ClientAdapter) Ack(b []byte) error {
119 | return a.snapdClient.Ack(b)
120 | }
121 |
122 | // Known queries assertions with type assertTypeName and matching assertion headers.
123 | func (a *ClientAdapter) Known(assertTypeName string, headers map[string]string) ([]asserts.Assertion, error) {
124 | return a.snapdClient.Known(assertTypeName, headers, nil)
125 | }
126 |
127 | // Conf gets the snap's current configuration
128 | func (a *ClientAdapter) Conf(name string) (map[string]interface{}, error) {
129 | return a.snapdClient.Conf(name, []string{})
130 | }
131 |
132 | // SetConf requests a snap to apply the provided patch to the configuration
133 | func (a *ClientAdapter) SetConf(name string, patch map[string]interface{}) (string, error) {
134 | return a.snapdClient.SetConf(name, patch)
135 | }
136 |
--------------------------------------------------------------------------------
/snapdapi/testing_client.go:
--------------------------------------------------------------------------------
1 | // -*- Mode: Go; indent-tabs-mode: t -*-
2 |
3 | /*
4 | * This file is part of the IoT Agent
5 | * Copyright 2019 Canonical Ltd.
6 | *
7 | * This program is free software: you can redistribute it and/or modify it
8 | * under the terms of the GNU General Public License version 3, as
9 | * published by the Free Software Foundation.
10 | *
11 | * This program is distributed in the hope that it will be useful, but WITHOUT
12 | * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
13 | * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.
14 | * See the GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | package snapdapi
21 |
22 | import (
23 | "bytes"
24 | "fmt"
25 | "github.com/snapcore/snapd/asserts"
26 | "github.com/snapcore/snapd/client"
27 | )
28 |
29 | const model1 = `type: model
30 | authority-id: canonical
31 | series: 16
32 | brand-id: canonical
33 | model: ubuntu-core-18-amd64
34 | architecture: amd64
35 | base: core18
36 | display-name: Ubuntu Core 18 (amd64)
37 | gadget: pc=18
38 | kernel: pc-kernel=18
39 | timestamp: 2018-08-13T09:00:00+00:00
40 | sign-key-sha3-384: 9tydnLa6MTJ-jaQTFUXEwHl1yRx7ZS4K5cyFDhYDcPzhS7uyEkDxdUjg9g08BtNn
41 | AcLBXAQAAQoABgUCW37NBwAKCRDgT5vottzAEut9D/4u9lD3lFWXoHx1VQT+mUCROcFHdXQBY/PJ
42 | NriRiDwBaOjEo5mvHMRJ2UulWvHnwqyMJctJKBP+RCKlrJEPX8eaLP/lmihwIiFfmzm49BLaNwli
43 | si0entond1sVWfiNr7azXoEuAIgYvxmJIvE+GZADDT0/OTFQRcLU69bhNEAQKBnkT0y/HTpuXwlJ
44 | TuwwJtDR0vZuFtwzj6Bdx7W42+vGmuXE7M4Ni6HUySNKYByB5BsrDf3/79p8huXyBtnWp+HBsHtb
45 | fgjzQoBcspj65Gi+crBrJ4jS+nfowRRVXLL1clXJOJLz12za+kN0/FC0PhussiQb5UI7USXJ+RvA
46 | Y8U1vrqG7bG5GYGqe1KB9GbLEm+GBPQZcZI3jRmm9V7tm9OWQzK98/uPwTD73IW7LrDT35WQrIYM
47 | fBfThJcRqpgzwZD/CBx82maLB9tmsRF5Mhcj2H1v7cn8nSkbv7+cCzh25lKv48Vqz1WTgO3HMPWW
48 | 0kb6BSoC+YGpstSUslqtpLdY/MfFI0DhshH2Y+h0c9/g4mux/Zb8Gs9V55HGn9mr2KKDmHsU2k+C
49 | maZWcXOxRpverZ2Pi9L4fZxhZ9H+FDcMGiHn2vJFQhI3u+LiK3aUUAov4k3vNRPGSvi1AGhuEtUa
50 | NG54bznx12KgOT3+YiHtfE95WiXUcJUrEXAgfVBVoA==`
51 |
52 | const serial1 = `type: serial
53 | authority-id: canonical
54 | brand-id: canonical
55 | model: ubuntu-core-18-amd64
56 | serial: d75f7300-abbf-4c11-bf0a-8b7103038490
57 | device-key:
58 | AcbBTQRWhcGAARAA05GC1FmdsBVDxd2DbolPLiqnQXDDwW0RScEcuG5ONGMmvolfS4DJxS5ONBq2
59 | ZdvGYoCzuSE4P/fruKwrfnR+DRn+frA2YAQOagHy2xmSYlXBz1wyDAvKVmJdv7Q2EjGK4K6vgVMn
60 | v8No+9/fecoIF7oa9kF7EwcnDrN89VGR+jOljGvwJ3QKHh8Tq5szL3ETlhdv4E6GEt4lEjcw3hDM
61 | rjGezRwM9riypbJp3paNWygff03sC6Q5esZk9U2ijF7tEF7CT5zCZEaLs+OdOQxYL6R4Bw7lp2h2
62 | xj/0G6pX3AH/VtijIJj/aOn6fBQB9kzGEghjUemHKqfpJ7lEH/TQ0JIMj9z/Tgj5KDPXEgtwgf78
63 | 37TYbDxcfoFJbi4sMoXFoKq2d2b8ufnQ1UlxMiCxr/z3GtraxDhMRx34vxIr1RqhHGt48as0rLjF
64 | mnsOAxSOhyloVgd9V5jdK7gzCi6aTtNZTMJV5TkGo3HyMEmDmj+TLAmPrENVt2A/EnKEyORz+0o1
65 | 5qtauqdcypOyAQc1aPmbGtqX5adI8tuj6JLxXdcQgCsQp+F5j+NM9TZnNnbwjkWZam1G8seGH+GZ
66 | QpeT5+5VqhXIkmlk8Mfqgn5br/1D7dfjBrzAumBpOmcOIeCCYrBtlpva4+nnO3Hp6bmkfuYBNXZe
67 | jJJS3M6FTNApbr0AEQEAAQ==
68 | device-key-sha3-384: xm9bu3yCuJguaB233yCAnXDE9zgOu8V39-2j8c-Rk0R27HjQpruF8ce_vGZDEm-G
69 | timestamp: 2019-01-10T17:40:44.771564Z
70 | sign-key-sha3-384: BWDEoaqyr25nF5SNCvEv2v7QnM9QsfCc0PBMYD_i2NGSQ32EF2d4D0hqUel3m8ul
71 | AcLBUgQAAQoABgUCXDeDnAAAnLMQAG6jJOffkqDrUhbgMP6VBmGr9nTm54fUg+pMYvxVxex6o4vH
72 | thA5qtQE9of1UVAK5qX7qwwl3rsIZ1/ESagW1ME1hyrCcVxcZ63BQrLODj9VX0kp8VmBvgUWGIsw
73 | sS/ZidF4lbsanWyzFefCErgzAncjxGN9cpMUsJPd5ai2c6Iq9+8qvJoT6ubWWg0Nh/Fe+jURKTs8
74 | Sfzfz0vaySoSmuH4cOYShz2tYvVEVvJyaoNt5vLUrG2TKgA5tz1S0mKwhwDbGRwKFL6mQSlJ/L5N
75 | P6UKSpZKfin+/ziH5YV0PoY3pTeTbuoMQWknYqQUBN/rHzd1y6xmY6rcWsZkFN2sPqA57ZgxUW4C
76 | h/3TZDyRUNXSGqiam5lKEx1EUWiWHhZG6TtOG8+pOW+Y+uW8v1c2qKKHIghQHAgZjUzaNyec2Ylw
77 | PfZW5UO8ua37jvSDV4aYcDXLlumD76mCQkXslltXATOnH9ZDMaf7/MRnx7Dwaqu0kuYUCNSWN/kJ
78 | oe5AnCaMg/yTp0EbV9ZlHNeQYGesUkhT9ULXzsUEfhs3S6mQtnC12O1C/F7fsv1x7lSa4WvPzlb7
79 | Azds7xIR91OzXGFMx/PO7ZwflxBRIZw7+iFXEXWzfhzVlrUFDLr8K++g1g563UzY9P86XwGDlS7l
80 | /PVxRaD/Ruiw0ey94zCcn3ROBEs/`
81 |
82 | // MockClient is a mock snapd API client for testing
83 | type MockClient struct {
84 | WithError bool
85 | }
86 |
87 | // Snap mocks the details of a snap
88 | func (c *MockClient) Snap(name string) (*client.Snap, *client.ResultInfo, error) {
89 | if name == "invalid" {
90 | return nil, nil, fmt.Errorf("MOCK error install")
91 | }
92 | return &client.Snap{
93 | ID: "1",
94 | Title: "helloworld",
95 | Summary: "Welcomes the world",
96 | }, &client.ResultInfo{}, nil
97 | }
98 |
99 | // List lists installed snaps
100 | func (c *MockClient) List(names []string, opts *client.ListOptions) ([]*client.Snap, error) {
101 | if c.WithError {
102 | return nil, fmt.Errorf("MOCK error snap list")
103 | }
104 | return []*client.Snap{
105 | {
106 | ID: "1",
107 | Title: "helloworld",
108 | Summary: "Welcomes the world",
109 | },
110 | }, nil
111 | }
112 |
113 | // Install mocks the snap installation
114 | func (c *MockClient) Install(name string, options *client.SnapOptions) (string, error) {
115 | if name == "invalid" {
116 | return "", fmt.Errorf("MOCK error install")
117 | }
118 | return "100", nil
119 | }
120 |
121 | // Refresh refreshes an existing snap
122 | func (c *MockClient) Refresh(name string, options *client.SnapOptions) (string, error) {
123 | if name == "invalid" {
124 | return "", fmt.Errorf("MOCK error refresh")
125 | }
126 | return "102", nil
127 | }
128 |
129 | // Revert reverts an existing snap
130 | func (c *MockClient) Revert(name string, options *client.SnapOptions) (string, error) {
131 | if name == "invalid" {
132 | return "", fmt.Errorf("MOCK error revert")
133 | }
134 | return "103", nil
135 | }
136 |
137 | // Remove mocks a snap removal
138 | func (c *MockClient) Remove(name string, options *client.SnapOptions) (string, error) {
139 | if name == "invalid" {
140 | return "", fmt.Errorf("MOCK error remove")
141 | }
142 | return "101", nil
143 | }
144 |
145 | // Enable mocks a snap enable
146 | func (c *MockClient) Enable(name string, options *client.SnapOptions) (string, error) {
147 | if name == "invalid" {
148 | return "", fmt.Errorf("MOCK error enable")
149 | }
150 | return "104", nil
151 | }
152 |
153 | // Disable mocks a snap disable
154 | func (c *MockClient) Disable(name string, options *client.SnapOptions) (string, error) {
155 | if name == "invalid" {
156 | return "", fmt.Errorf("MOCK error disable")
157 | }
158 | return "105", nil
159 | }
160 |
161 | // ServerVersion mocks the server version call
162 | func (c *MockClient) ServerVersion() (*client.ServerVersion, error) {
163 | if c.WithError {
164 | return nil, fmt.Errorf("MOCK error server version")
165 | }
166 | return &client.ServerVersion{
167 | Version: "1.0",
168 | KernelVersion: "generic-kernel.5.0",
169 | }, nil
170 | }
171 |
172 | // Ack mocks adding an assertion
173 | func (c *MockClient) Ack(b []byte) error {
174 | if bytes.Equal(b, []byte("invalid")) {
175 | return fmt.Errorf("MOCK error ack")
176 | }
177 | return nil
178 | }
179 |
180 | // Known returns the known assertions for a given type
181 | func (c *MockClient) Known(assertTypeName string, headers map[string]string) ([]asserts.Assertion, error) {
182 | panic("implement me")
183 | }
184 |
185 | // Conf mocks returning config
186 | func (c *MockClient) Conf(name string) (map[string]interface{}, error) {
187 | if name == "invalid" {
188 | return nil, fmt.Errorf("MOCK error conf")
189 | }
190 | return map[string]interface{}{"setting": "value"}, nil
191 | }
192 |
193 | // SetConf mocks setting the config
194 | func (c *MockClient) SetConf(name string, patch map[string]interface{}) (string, error) {
195 | if name == "invalid" {
196 | return "106", fmt.Errorf("MOCK error set conf")
197 | }
198 | return "106", nil
199 | }
200 |
201 | // GetEncodedAssertions returns the encoded model and serial assertions
202 | func (c *MockClient) GetEncodedAssertions() ([]byte, error) {
203 | if c.WithError {
204 | return nil, fmt.Errorf("MOCK error known")
205 | }
206 | return []byte(fmt.Sprintf("%s\n%s", model1, serial1)), nil
207 | }
208 |
209 | // DeviceInfo returns a mock device details
210 | func (c *MockClient) DeviceInfo() (ActionDevice, error) {
211 | if c.WithError {
212 | return ActionDevice{}, fmt.Errorf("MOCK error device info")
213 | }
214 | return ActionDevice{
215 | Brand: "example",
216 | Model: "drone-1000",
217 | SerialNumber: "A11111111",
218 | DeviceKey: "AAAAAAAAAA",
219 | StoreID: "example-store",
220 | }, nil
221 | }
222 |
--------------------------------------------------------------------------------