Merge ~ballot/charm-k8s-mm-pd-bot/+git/charm-k8s-mm-pd-bot:master into charm-k8s-mm-pd-bot:master

Proposed by Benjamin Allot
Status: Superseded
Proposed branch: ~ballot/charm-k8s-mm-pd-bot/+git/charm-k8s-mm-pd-bot:master
Merge into: charm-k8s-mm-pd-bot:master
Diff against target: 1222 lines (+1050/-59)
9 files modified
.gitignore (+7/-0)
.jujuignore (+10/-0)
COPYRIGHT (+16/-0)
LICENSE (+675/-0)
README.md (+98/-0)
config.yaml (+36/-31)
examples/bot.cfg (+48/-0)
requirements.txt (+1/-0)
src/charm.py (+159/-28)
Reviewer Review Type Date Requested Status
MatterMost Pagerduty Bot Charmers Pending
Review via email: mp+388322@code.launchpad.net
To post a comment you must log in.
Revision history for this message
Tom Haddon (mthaddon) wrote :

Not a full review as it's still a WIP branch, but some comments inline

4ba2c6d... by Benjamin Allot

Add license related parts

2c17b5d... by Benjamin Allot

Add .jujuignore to avoid unecessary files during charmcraft build

Revision history for this message
Benjamin Allot (ballot) wrote :

I've seen the comments, will address them (currently working and squashing, will cut the list of commit down to charm work only later on)

5e23a72... by Benjamin Allot

Add a configuration example for the bot

9d534ff... by Benjamin Allot

A working charm with some basic manual test

* currently able to spawn a mm-pd-bot and have an ingess (tested locally
  only) without TLS
* Some check in the configuration provided will set the blocked status
  if not provided (see the README.md)

TODO:
* add a healthcheck to the pod (will probably required modification of
the bot)
* write tests
* test ingress with TLS

Unmerged commits

9d534ff... by Benjamin Allot

A working charm with some basic manual test

* currently able to spawn a mm-pd-bot and have an ingess (tested locally
  only) without TLS
* Some check in the configuration provided will set the blocked status
  if not provided (see the README.md)

TODO:
* add a healthcheck to the pod (will probably required modification of
the bot)
* write tests
* test ingress with TLS

2c17b5d... by Benjamin Allot

Add .jujuignore to avoid unecessary files during charmcraft build

4ba2c6d... by Benjamin Allot

Add license related parts

e525396... by Benjamin Allot

Basic README with steps to test the charm

5e23a72... by Benjamin Allot

Add a configuration example for the bot

8c17fe9... by Benjamin Allot

Add .gitignore file

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1diff --git a/.gitignore b/.gitignore
2new file mode 100644
3index 0000000..f0d9170
4--- /dev/null
5+++ b/.gitignore
6@@ -0,0 +1,7 @@
7+*.swp
8+/.tox
9+/build
10+/mm-pd-bot.charm
11+__pycache__
12+bot.cfg
13+!/examples/bot.cfg
14diff --git a/.jujuignore b/.jujuignore
15new file mode 100644
16index 0000000..16d5c57
17--- /dev/null
18+++ b/.jujuignore
19@@ -0,0 +1,10 @@
20+*.swp
21+.coverage
22+.tox
23+/.git
24+/.jujuignore
25+/Makefile
26+/build
27+/tests
28+__pycache__
29+bot.cfg
30diff --git a/COPYRIGHT b/COPYRIGHT
31new file mode 100644
32index 0000000..1889423
33--- /dev/null
34+++ b/COPYRIGHT
35@@ -0,0 +1,16 @@
36+Format: http://dep.debian.net/deps/dep5/
37+
38+Files: *
39+Copyright: Copyright 2020, Canonical Ltd.
40+License: GPL-3
41+ This program is free software: you can redistribute it and/or modify
42+ it under the terms of the GNU General Public License version 3, as
43+ published by the Free Software Foundation.
44+ .
45+ This program is distributed in the hope that it will be useful,
46+ but WITHOUT ANY WARRANTY; without even the implied warranties of
47+ MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
48+ PURPOSE. See the GNU General Public License for more details.
49+ .
50+ You should have received a copy of the GNU General Public License
51+ along with this program. If not, see <http://www.gnu.org/licenses/>.
52diff --git a/LICENSE b/LICENSE
53new file mode 100644
54index 0000000..53d1f3d
55--- /dev/null
56+++ b/LICENSE
57@@ -0,0 +1,675 @@
58+ GNU GENERAL PUBLIC LICENSE
59+ Version 3, 29 June 2007
60+
61+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
62+ Everyone is permitted to copy and distribute verbatim copies
63+ of this license document, but changing it is not allowed.
64+
65+ Preamble
66+
67+ The GNU General Public License is a free, copyleft license for
68+software and other kinds of works.
69+
70+ The licenses for most software and other practical works are designed
71+to take away your freedom to share and change the works. By contrast,
72+the GNU General Public License is intended to guarantee your freedom to
73+share and change all versions of a program--to make sure it remains free
74+software for all its users. We, the Free Software Foundation, use the
75+GNU General Public License for most of our software; it applies also to
76+any other work released this way by its authors. You can apply it to
77+your programs, too.
78+
79+ When we speak of free software, we are referring to freedom, not
80+price. Our General Public Licenses are designed to make sure that you
81+have the freedom to distribute copies of free software (and charge for
82+them if you wish), that you receive source code or can get it if you
83+want it, that you can change the software or use pieces of it in new
84+free programs, and that you know you can do these things.
85+
86+ To protect your rights, we need to prevent others from denying you
87+these rights or asking you to surrender the rights. Therefore, you have
88+certain responsibilities if you distribute copies of the software, or if
89+you modify it: responsibilities to respect the freedom of others.
90+
91+ For example, if you distribute copies of such a program, whether
92+gratis or for a fee, you must pass on to the recipients the same
93+freedoms that you received. You must make sure that they, too, receive
94+or can get the source code. And you must show them these terms so they
95+know their rights.
96+
97+ Developers that use the GNU GPL protect your rights with two steps:
98+(1) assert copyright on the software, and (2) offer you this License
99+giving you legal permission to copy, distribute and/or modify it.
100+
101+ For the developers' and authors' protection, the GPL clearly explains
102+that there is no warranty for this free software. For both users' and
103+authors' sake, the GPL requires that modified versions be marked as
104+changed, so that their problems will not be attributed erroneously to
105+authors of previous versions.
106+
107+ Some devices are designed to deny users access to install or run
108+modified versions of the software inside them, although the manufacturer
109+can do so. This is fundamentally incompatible with the aim of
110+protecting users' freedom to change the software. The systematic
111+pattern of such abuse occurs in the area of products for individuals to
112+use, which is precisely where it is most unacceptable. Therefore, we
113+have designed this version of the GPL to prohibit the practice for those
114+products. If such problems arise substantially in other domains, we
115+stand ready to extend this provision to those domains in future versions
116+of the GPL, as needed to protect the freedom of users.
117+
118+ Finally, every program is threatened constantly by software patents.
119+States should not allow patents to restrict development and use of
120+software on general-purpose computers, but in those that do, we wish to
121+avoid the special danger that patents applied to a free program could
122+make it effectively proprietary. To prevent this, the GPL assures that
123+patents cannot be used to render the program non-free.
124+
125+ The precise terms and conditions for copying, distribution and
126+modification follow.
127+
128+ TERMS AND CONDITIONS
129+
130+ 0. Definitions.
131+
132+ "This License" refers to version 3 of the GNU General Public License.
133+
134+ "Copyright" also means copyright-like laws that apply to other kinds of
135+works, such as semiconductor masks.
136+
137+ "The Program" refers to any copyrightable work licensed under this
138+License. Each licensee is addressed as "you". "Licensees" and
139+"recipients" may be individuals or organizations.
140+
141+ To "modify" a work means to copy from or adapt all or part of the work
142+in a fashion requiring copyright permission, other than the making of an
143+exact copy. The resulting work is called a "modified version" of the
144+earlier work or a work "based on" the earlier work.
145+
146+ A "covered work" means either the unmodified Program or a work based
147+on the Program.
148+
149+ To "propagate" a work means to do anything with it that, without
150+permission, would make you directly or secondarily liable for
151+infringement under applicable copyright law, except executing it on a
152+computer or modifying a private copy. Propagation includes copying,
153+distribution (with or without modification), making available to the
154+public, and in some countries other activities as well.
155+
156+ To "convey" a work means any kind of propagation that enables other
157+parties to make or receive copies. Mere interaction with a user through
158+a computer network, with no transfer of a copy, is not conveying.
159+
160+ An interactive user interface displays "Appropriate Legal Notices"
161+to the extent that it includes a convenient and prominently visible
162+feature that (1) displays an appropriate copyright notice, and (2)
163+tells the user that there is no warranty for the work (except to the
164+extent that warranties are provided), that licensees may convey the
165+work under this License, and how to view a copy of this License. If
166+the interface presents a list of user commands or options, such as a
167+menu, a prominent item in the list meets this criterion.
168+
169+ 1. Source Code.
170+
171+ The "source code" for a work means the preferred form of the work
172+for making modifications to it. "Object code" means any non-source
173+form of a work.
174+
175+ A "Standard Interface" means an interface that either is an official
176+standard defined by a recognized standards body, or, in the case of
177+interfaces specified for a particular programming language, one that
178+is widely used among developers working in that language.
179+
180+ The "System Libraries" of an executable work include anything, other
181+than the work as a whole, that (a) is included in the normal form of
182+packaging a Major Component, but which is not part of that Major
183+Component, and (b) serves only to enable use of the work with that
184+Major Component, or to implement a Standard Interface for which an
185+implementation is available to the public in source code form. A
186+"Major Component", in this context, means a major essential component
187+(kernel, window system, and so on) of the specific operating system
188+(if any) on which the executable work runs, or a compiler used to
189+produce the work, or an object code interpreter used to run it.
190+
191+ The "Corresponding Source" for a work in object code form means all
192+the source code needed to generate, install, and (for an executable
193+work) run the object code and to modify the work, including scripts to
194+control those activities. However, it does not include the work's
195+System Libraries, or general-purpose tools or generally available free
196+programs which are used unmodified in performing those activities but
197+which are not part of the work. For example, Corresponding Source
198+includes interface definition files associated with source files for
199+the work, and the source code for shared libraries and dynamically
200+linked subprograms that the work is specifically designed to require,
201+such as by intimate data communication or control flow between those
202+subprograms and other parts of the work.
203+
204+ The Corresponding Source need not include anything that users
205+can regenerate automatically from other parts of the Corresponding
206+Source.
207+
208+ The Corresponding Source for a work in source code form is that
209+same work.
210+
211+ 2. Basic Permissions.
212+
213+ All rights granted under this License are granted for the term of
214+copyright on the Program, and are irrevocable provided the stated
215+conditions are met. This License explicitly affirms your unlimited
216+permission to run the unmodified Program. The output from running a
217+covered work is covered by this License only if the output, given its
218+content, constitutes a covered work. This License acknowledges your
219+rights of fair use or other equivalent, as provided by copyright law.
220+
221+ You may make, run and propagate covered works that you do not
222+convey, without conditions so long as your license otherwise remains
223+in force. You may convey covered works to others for the sole purpose
224+of having them make modifications exclusively for you, or provide you
225+with facilities for running those works, provided that you comply with
226+the terms of this License in conveying all material for which you do
227+not control copyright. Those thus making or running the covered works
228+for you must do so exclusively on your behalf, under your direction
229+and control, on terms that prohibit them from making any copies of
230+your copyrighted material outside their relationship with you.
231+
232+ Conveying under any other circumstances is permitted solely under
233+the conditions stated below. Sublicensing is not allowed; section 10
234+makes it unnecessary.
235+
236+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
237+
238+ No covered work shall be deemed part of an effective technological
239+measure under any applicable law fulfilling obligations under article
240+11 of the WIPO copyright treaty adopted on 20 December 1996, or
241+similar laws prohibiting or restricting circumvention of such
242+measures.
243+
244+ When you convey a covered work, you waive any legal power to forbid
245+circumvention of technological measures to the extent such circumvention
246+is effected by exercising rights under this License with respect to
247+the covered work, and you disclaim any intention to limit operation or
248+modification of the work as a means of enforcing, against the work's
249+users, your or third parties' legal rights to forbid circumvention of
250+technological measures.
251+
252+ 4. Conveying Verbatim Copies.
253+
254+ You may convey verbatim copies of the Program's source code as you
255+receive it, in any medium, provided that you conspicuously and
256+appropriately publish on each copy an appropriate copyright notice;
257+keep intact all notices stating that this License and any
258+non-permissive terms added in accord with section 7 apply to the code;
259+keep intact all notices of the absence of any warranty; and give all
260+recipients a copy of this License along with the Program.
261+
262+ You may charge any price or no price for each copy that you convey,
263+and you may offer support or warranty protection for a fee.
264+
265+ 5. Conveying Modified Source Versions.
266+
267+ You may convey a work based on the Program, or the modifications to
268+produce it from the Program, in the form of source code under the
269+terms of section 4, provided that you also meet all of these conditions:
270+
271+ a) The work must carry prominent notices stating that you modified
272+ it, and giving a relevant date.
273+
274+ b) The work must carry prominent notices stating that it is
275+ released under this License and any conditions added under section
276+ 7. This requirement modifies the requirement in section 4 to
277+ "keep intact all notices".
278+
279+ c) You must license the entire work, as a whole, under this
280+ License to anyone who comes into possession of a copy. This
281+ License will therefore apply, along with any applicable section 7
282+ additional terms, to the whole of the work, and all its parts,
283+ regardless of how they are packaged. This License gives no
284+ permission to license the work in any other way, but it does not
285+ invalidate such permission if you have separately received it.
286+
287+ d) If the work has interactive user interfaces, each must display
288+ Appropriate Legal Notices; however, if the Program has interactive
289+ interfaces that do not display Appropriate Legal Notices, your
290+ work need not make them do so.
291+
292+ A compilation of a covered work with other separate and independent
293+works, which are not by their nature extensions of the covered work,
294+and which are not combined with it such as to form a larger program,
295+in or on a volume of a storage or distribution medium, is called an
296+"aggregate" if the compilation and its resulting copyright are not
297+used to limit the access or legal rights of the compilation's users
298+beyond what the individual works permit. Inclusion of a covered work
299+in an aggregate does not cause this License to apply to the other
300+parts of the aggregate.
301+
302+ 6. Conveying Non-Source Forms.
303+
304+ You may convey a covered work in object code form under the terms
305+of sections 4 and 5, provided that you also convey the
306+machine-readable Corresponding Source under the terms of this License,
307+in one of these ways:
308+
309+ a) Convey the object code in, or embodied in, a physical product
310+ (including a physical distribution medium), accompanied by the
311+ Corresponding Source fixed on a durable physical medium
312+ customarily used for software interchange.
313+
314+ b) Convey the object code in, or embodied in, a physical product
315+ (including a physical distribution medium), accompanied by a
316+ written offer, valid for at least three years and valid for as
317+ long as you offer spare parts or customer support for that product
318+ model, to give anyone who possesses the object code either (1) a
319+ copy of the Corresponding Source for all the software in the
320+ product that is covered by this License, on a durable physical
321+ medium customarily used for software interchange, for a price no
322+ more than your reasonable cost of physically performing this
323+ conveying of source, or (2) access to copy the
324+ Corresponding Source from a network server at no charge.
325+
326+ c) Convey individual copies of the object code with a copy of the
327+ written offer to provide the Corresponding Source. This
328+ alternative is allowed only occasionally and noncommercially, and
329+ only if you received the object code with such an offer, in accord
330+ with subsection 6b.
331+
332+ d) Convey the object code by offering access from a designated
333+ place (gratis or for a charge), and offer equivalent access to the
334+ Corresponding Source in the same way through the same place at no
335+ further charge. You need not require recipients to copy the
336+ Corresponding Source along with the object code. If the place to
337+ copy the object code is a network server, the Corresponding Source
338+ may be on a different server (operated by you or a third party)
339+ that supports equivalent copying facilities, provided you maintain
340+ clear directions next to the object code saying where to find the
341+ Corresponding Source. Regardless of what server hosts the
342+ Corresponding Source, you remain obligated to ensure that it is
343+ available for as long as needed to satisfy these requirements.
344+
345+ e) Convey the object code using peer-to-peer transmission, provided
346+ you inform other peers where the object code and Corresponding
347+ Source of the work are being offered to the general public at no
348+ charge under subsection 6d.
349+
350+ A separable portion of the object code, whose source code is excluded
351+from the Corresponding Source as a System Library, need not be
352+included in conveying the object code work.
353+
354+ A "User Product" is either (1) a "consumer product", which means any
355+tangible personal property which is normally used for personal, family,
356+or household purposes, or (2) anything designed or sold for incorporation
357+into a dwelling. In determining whether a product is a consumer product,
358+doubtful cases shall be resolved in favor of coverage. For a particular
359+product received by a particular user, "normally used" refers to a
360+typical or common use of that class of product, regardless of the status
361+of the particular user or of the way in which the particular user
362+actually uses, or expects or is expected to use, the product. A product
363+is a consumer product regardless of whether the product has substantial
364+commercial, industrial or non-consumer uses, unless such uses represent
365+the only significant mode of use of the product.
366+
367+ "Installation Information" for a User Product means any methods,
368+procedures, authorization keys, or other information required to install
369+and execute modified versions of a covered work in that User Product from
370+a modified version of its Corresponding Source. The information must
371+suffice to ensure that the continued functioning of the modified object
372+code is in no case prevented or interfered with solely because
373+modification has been made.
374+
375+ If you convey an object code work under this section in, or with, or
376+specifically for use in, a User Product, and the conveying occurs as
377+part of a transaction in which the right of possession and use of the
378+User Product is transferred to the recipient in perpetuity or for a
379+fixed term (regardless of how the transaction is characterized), the
380+Corresponding Source conveyed under this section must be accompanied
381+by the Installation Information. But this requirement does not apply
382+if neither you nor any third party retains the ability to install
383+modified object code on the User Product (for example, the work has
384+been installed in ROM).
385+
386+ The requirement to provide Installation Information does not include a
387+requirement to continue to provide support service, warranty, or updates
388+for a work that has been modified or installed by the recipient, or for
389+the User Product in which it has been modified or installed. Access to a
390+network may be denied when the modification itself materially and
391+adversely affects the operation of the network or violates the rules and
392+protocols for communication across the network.
393+
394+ Corresponding Source conveyed, and Installation Information provided,
395+in accord with this section must be in a format that is publicly
396+documented (and with an implementation available to the public in
397+source code form), and must require no special password or key for
398+unpacking, reading or copying.
399+
400+ 7. Additional Terms.
401+
402+ "Additional permissions" are terms that supplement the terms of this
403+License by making exceptions from one or more of its conditions.
404+Additional permissions that are applicable to the entire Program shall
405+be treated as though they were included in this License, to the extent
406+that they are valid under applicable law. If additional permissions
407+apply only to part of the Program, that part may be used separately
408+under those permissions, but the entire Program remains governed by
409+this License without regard to the additional permissions.
410+
411+ When you convey a copy of a covered work, you may at your option
412+remove any additional permissions from that copy, or from any part of
413+it. (Additional permissions may be written to require their own
414+removal in certain cases when you modify the work.) You may place
415+additional permissions on material, added by you to a covered work,
416+for which you have or can give appropriate copyright permission.
417+
418+ Notwithstanding any other provision of this License, for material you
419+add to a covered work, you may (if authorized by the copyright holders of
420+that material) supplement the terms of this License with terms:
421+
422+ a) Disclaiming warranty or limiting liability differently from the
423+ terms of sections 15 and 16 of this License; or
424+
425+ b) Requiring preservation of specified reasonable legal notices or
426+ author attributions in that material or in the Appropriate Legal
427+ Notices displayed by works containing it; or
428+
429+ c) Prohibiting misrepresentation of the origin of that material, or
430+ requiring that modified versions of such material be marked in
431+ reasonable ways as different from the original version; or
432+
433+ d) Limiting the use for publicity purposes of names of licensors or
434+ authors of the material; or
435+
436+ e) Declining to grant rights under trademark law for use of some
437+ trade names, trademarks, or service marks; or
438+
439+ f) Requiring indemnification of licensors and authors of that
440+ material by anyone who conveys the material (or modified versions of
441+ it) with contractual assumptions of liability to the recipient, for
442+ any liability that these contractual assumptions directly impose on
443+ those licensors and authors.
444+
445+ All other non-permissive additional terms are considered "further
446+restrictions" within the meaning of section 10. If the Program as you
447+received it, or any part of it, contains a notice stating that it is
448+governed by this License along with a term that is a further
449+restriction, you may remove that term. If a license document contains
450+a further restriction but permits relicensing or conveying under this
451+License, you may add to a covered work material governed by the terms
452+of that license document, provided that the further restriction does
453+not survive such relicensing or conveying.
454+
455+ If you add terms to a covered work in accord with this section, you
456+must place, in the relevant source files, a statement of the
457+additional terms that apply to those files, or a notice indicating
458+where to find the applicable terms.
459+
460+ Additional terms, permissive or non-permissive, may be stated in the
461+form of a separately written license, or stated as exceptions;
462+the above requirements apply either way.
463+
464+ 8. Termination.
465+
466+ You may not propagate or modify a covered work except as expressly
467+provided under this License. Any attempt otherwise to propagate or
468+modify it is void, and will automatically terminate your rights under
469+this License (including any patent licenses granted under the third
470+paragraph of section 11).
471+
472+ However, if you cease all violation of this License, then your
473+license from a particular copyright holder is reinstated (a)
474+provisionally, unless and until the copyright holder explicitly and
475+finally terminates your license, and (b) permanently, if the copyright
476+holder fails to notify you of the violation by some reasonable means
477+prior to 60 days after the cessation.
478+
479+ Moreover, your license from a particular copyright holder is
480+reinstated permanently if the copyright holder notifies you of the
481+violation by some reasonable means, this is the first time you have
482+received notice of violation of this License (for any work) from that
483+copyright holder, and you cure the violation prior to 30 days after
484+your receipt of the notice.
485+
486+ Termination of your rights under this section does not terminate the
487+licenses of parties who have received copies or rights from you under
488+this License. If your rights have been terminated and not permanently
489+reinstated, you do not qualify to receive new licenses for the same
490+material under section 10.
491+
492+ 9. Acceptance Not Required for Having Copies.
493+
494+ You are not required to accept this License in order to receive or
495+run a copy of the Program. Ancillary propagation of a covered work
496+occurring solely as a consequence of using peer-to-peer transmission
497+to receive a copy likewise does not require acceptance. However,
498+nothing other than this License grants you permission to propagate or
499+modify any covered work. These actions infringe copyright if you do
500+not accept this License. Therefore, by modifying or propagating a
501+covered work, you indicate your acceptance of this License to do so.
502+
503+ 10. Automatic Licensing of Downstream Recipients.
504+
505+ Each time you convey a covered work, the recipient automatically
506+receives a license from the original licensors, to run, modify and
507+propagate that work, subject to this License. You are not responsible
508+for enforcing compliance by third parties with this License.
509+
510+ An "entity transaction" is a transaction transferring control of an
511+organization, or substantially all assets of one, or subdividing an
512+organization, or merging organizations. If propagation of a covered
513+work results from an entity transaction, each party to that
514+transaction who receives a copy of the work also receives whatever
515+licenses to the work the party's predecessor in interest had or could
516+give under the previous paragraph, plus a right to possession of the
517+Corresponding Source of the work from the predecessor in interest, if
518+the predecessor has it or can get it with reasonable efforts.
519+
520+ You may not impose any further restrictions on the exercise of the
521+rights granted or affirmed under this License. For example, you may
522+not impose a license fee, royalty, or other charge for exercise of
523+rights granted under this License, and you may not initiate litigation
524+(including a cross-claim or counterclaim in a lawsuit) alleging that
525+any patent claim is infringed by making, using, selling, offering for
526+sale, or importing the Program or any portion of it.
527+
528+ 11. Patents.
529+
530+ A "contributor" is a copyright holder who authorizes use under this
531+License of the Program or a work on which the Program is based. The
532+work thus licensed is called the contributor's "contributor version".
533+
534+ A contributor's "essential patent claims" are all patent claims
535+owned or controlled by the contributor, whether already acquired or
536+hereafter acquired, that would be infringed by some manner, permitted
537+by this License, of making, using, or selling its contributor version,
538+but do not include claims that would be infringed only as a
539+consequence of further modification of the contributor version. For
540+purposes of this definition, "control" includes the right to grant
541+patent sublicenses in a manner consistent with the requirements of
542+this License.
543+
544+ Each contributor grants you a non-exclusive, worldwide, royalty-free
545+patent license under the contributor's essential patent claims, to
546+make, use, sell, offer for sale, import and otherwise run, modify and
547+propagate the contents of its contributor version.
548+
549+ In the following three paragraphs, a "patent license" is any express
550+agreement or commitment, however denominated, not to enforce a patent
551+(such as an express permission to practice a patent or covenant not to
552+sue for patent infringement). To "grant" such a patent license to a
553+party means to make such an agreement or commitment not to enforce a
554+patent against the party.
555+
556+ If you convey a covered work, knowingly relying on a patent license,
557+and the Corresponding Source of the work is not available for anyone
558+to copy, free of charge and under the terms of this License, through a
559+publicly available network server or other readily accessible means,
560+then you must either (1) cause the Corresponding Source to be so
561+available, or (2) arrange to deprive yourself of the benefit of the
562+patent license for this particular work, or (3) arrange, in a manner
563+consistent with the requirements of this License, to extend the patent
564+license to downstream recipients. "Knowingly relying" means you have
565+actual knowledge that, but for the patent license, your conveying the
566+covered work in a country, or your recipient's use of the covered work
567+in a country, would infringe one or more identifiable patents in that
568+country that you have reason to believe are valid.
569+
570+ If, pursuant to or in connection with a single transaction or
571+arrangement, you convey, or propagate by procuring conveyance of, a
572+covered work, and grant a patent license to some of the parties
573+receiving the covered work authorizing them to use, propagate, modify
574+or convey a specific copy of the covered work, then the patent license
575+you grant is automatically extended to all recipients of the covered
576+work and works based on it.
577+
578+ A patent license is "discriminatory" if it does not include within
579+the scope of its coverage, prohibits the exercise of, or is
580+conditioned on the non-exercise of one or more of the rights that are
581+specifically granted under this License. You may not convey a covered
582+work if you are a party to an arrangement with a third party that is
583+in the business of distributing software, under which you make payment
584+to the third party based on the extent of your activity of conveying
585+the work, and under which the third party grants, to any of the
586+parties who would receive the covered work from you, a discriminatory
587+patent license (a) in connection with copies of the covered work
588+conveyed by you (or copies made from those copies), or (b) primarily
589+for and in connection with specific products or compilations that
590+contain the covered work, unless you entered into that arrangement,
591+or that patent license was granted, prior to 28 March 2007.
592+
593+ Nothing in this License shall be construed as excluding or limiting
594+any implied license or other defenses to infringement that may
595+otherwise be available to you under applicable patent law.
596+
597+ 12. No Surrender of Others' Freedom.
598+
599+ If conditions are imposed on you (whether by court order, agreement or
600+otherwise) that contradict the conditions of this License, they do not
601+excuse you from the conditions of this License. If you cannot convey a
602+covered work so as to satisfy simultaneously your obligations under this
603+License and any other pertinent obligations, then as a consequence you may
604+not convey it at all. For example, if you agree to terms that obligate you
605+to collect a royalty for further conveying from those to whom you convey
606+the Program, the only way you could satisfy both those terms and this
607+License would be to refrain entirely from conveying the Program.
608+
609+ 13. Use with the GNU Affero General Public License.
610+
611+ Notwithstanding any other provision of this License, you have
612+permission to link or combine any covered work with a work licensed
613+under version 3 of the GNU Affero General Public License into a single
614+combined work, and to convey the resulting work. The terms of this
615+License will continue to apply to the part which is the covered work,
616+but the special requirements of the GNU Affero General Public License,
617+section 13, concerning interaction through a network will apply to the
618+combination as such.
619+
620+ 14. Revised Versions of this License.
621+
622+ The Free Software Foundation may publish revised and/or new versions of
623+the GNU General Public License from time to time. Such new versions will
624+be similar in spirit to the present version, but may differ in detail to
625+address new problems or concerns.
626+
627+ Each version is given a distinguishing version number. If the
628+Program specifies that a certain numbered version of the GNU General
629+Public License "or any later version" applies to it, you have the
630+option of following the terms and conditions either of that numbered
631+version or of any later version published by the Free Software
632+Foundation. If the Program does not specify a version number of the
633+GNU General Public License, you may choose any version ever published
634+by the Free Software Foundation.
635+
636+ If the Program specifies that a proxy can decide which future
637+versions of the GNU General Public License can be used, that proxy's
638+public statement of acceptance of a version permanently authorizes you
639+to choose that version for the Program.
640+
641+ Later license versions may give you additional or different
642+permissions. However, no additional obligations are imposed on any
643+author or copyright holder as a result of your choosing to follow a
644+later version.
645+
646+ 15. Disclaimer of Warranty.
647+
648+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
649+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
650+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
651+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
652+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
653+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
654+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
655+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
656+
657+ 16. Limitation of Liability.
658+
659+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
660+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
661+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
662+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
663+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
664+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
665+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
666+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
667+SUCH DAMAGES.
668+
669+ 17. Interpretation of Sections 15 and 16.
670+
671+ If the disclaimer of warranty and limitation of liability provided
672+above cannot be given local legal effect according to their terms,
673+reviewing courts shall apply local law that most closely approximates
674+an absolute waiver of all civil liability in connection with the
675+Program, unless a warranty or assumption of liability accompanies a
676+copy of the Program in return for a fee.
677+
678+ END OF TERMS AND CONDITIONS
679+
680+ How to Apply These Terms to Your New Programs
681+
682+ If you develop a new program, and you want it to be of the greatest
683+possible use to the public, the best way to achieve this is to make it
684+free software which everyone can redistribute and change under these terms.
685+
686+ To do so, attach the following notices to the program. It is safest
687+to attach them to the start of each source file to most effectively
688+state the exclusion of warranty; and each file should have at least
689+the "copyright" line and a pointer to where the full notice is found.
690+
691+ <one line to give the program's name and a brief idea of what it does.>
692+ Copyright (C) <year> <name of author>
693+
694+ This program is free software: you can redistribute it and/or modify
695+ it under the terms of the GNU General Public License as published by
696+ the Free Software Foundation, either version 3 of the License, or
697+ (at your option) any later version.
698+
699+ This program is distributed in the hope that it will be useful,
700+ but WITHOUT ANY WARRANTY; without even the implied warranty of
701+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
702+ GNU General Public License for more details.
703+
704+ You should have received a copy of the GNU General Public License
705+ along with this program. If not, see <https://www.gnu.org/licenses/>.
706+
707+Also add information on how to contact you by electronic and paper mail.
708+
709+ If the program does terminal interaction, make it output a short
710+notice like this when it starts in an interactive mode:
711+
712+ <program> Copyright (C) <year> <name of author>
713+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
714+ This is free software, and you are welcome to redistribute it
715+ under certain conditions; type `show c' for details.
716+
717+The hypothetical commands `show w' and `show c' should show the appropriate
718+parts of the General Public License. Of course, your program's commands
719+might be different; for a GUI interface, you would use an "about box".
720+
721+ You should also get your employer (if you work as a programmer) or school,
722+if any, to sign a "copyright disclaimer" for the program, if necessary.
723+For more information on this, and how to apply and follow the GNU GPL, see
724+<https://www.gnu.org/licenses/>.
725+
726+ The GNU General Public License does not permit incorporating your program
727+into proprietary programs. If your program is a subroutine library, you
728+may consider it more useful to permit linking proprietary applications with
729+the library. If this is what you want to do, use the GNU Lesser General
730+Public License instead of this License. But first, please read
731+<https://www.gnu.org/licenses/why-not-lgpl.html>.
732+
733diff --git a/README.md b/README.md
734new file mode 100644
735index 0000000..fac805e
736--- /dev/null
737+++ b/README.md
738@@ -0,0 +1,98 @@
739+# MatterMost Pagerduty Bot charm
740+
741+A juju charm deploying Mattermost PagerDuty Bot, using [a custom-built built image](https://code.launchpad.net/~canonical-is/is-pd-bot/+git/mm-pd-bot),
742+
743+## Overview
744+
745+This is a k8s workload charm and can only be deployed to to a Juju k8s
746+cloud, attached to a controller using `juju add-k8s`.
747+
748+A valid configuration file will be needed. See [the example](https://git.launchpad.net/~ballot/charm-k8s-mm-pd-bot/+git/charm-k8s-mm-pd-bot/tree/examples/bot.cfg)
749+
750+## Details
751+
752+See config option descriptions in config.yaml.
753+
754+## Getting Started
755+
756+### Prepare your local environment
757+
758+Notes for deploying a test setup locally using microk8s:
759+
760+```
761+sudo snap install juju --classic
762+sudo snap install juju-wait --classic
763+sudo snap install microk8s --classic
764+sudo snap alias microk8s.kubectl kubectl
765+sudo snap install charmcraft
766+git clone https://git.launchpad.net/charm-k8s-mm-pd-bot
767+
768+microk8s.reset # Warning! Clean slate!
769+microk8s.enable dns dashboard registry storage
770+microk8s.status --wait-ready
771+
772+juju bootstrap microk8s micro
773+juju add-model mm-pd-bot
774+juju model-config logging-config="<root>=DEBUG"
775+make -C charm-k8s-mm-pd-bot mm-pd-bot.charm
776+```
777+
778+### Copy over the bot.cfg example
779+```
780+cp mm-pd-bot/examples/bot.cfg charm-k8s-mm-pd-bot/bot.cfg
781+```
782+
783+Be sure to have the right values in your bot.cfg file
784+You need the following section and option at least to have a working bot
785+```
786+[PagerDuty]
787+account = %(MM_PD_BOT_PD_ACCOUNT)s
788+api-token = %(MM_PD_BOT_PD_TOKEN)s
789+private-channel = %(MM_PD_BOT_PD_PRIVATE_CHANNEL)s
790+ppublic-channel = %(MM_PD_BOT_PD_PUBLIC_CHANNEL)s
791+# This one is optional but will avoid getting incident for ALL escalation policy under your PagerDuty account
792+filter-status-on-policy = ^(escalation Policy 1|escalation Policy 2)$
793+
794+[Prometheus]
795+max_cache_size = 100
796+
797+[httpd]
798+# This parameter will be used for the ingress value and is required
799+hostname = %(MM_PD_BOT_HOSTNAME)s
800+listen-ip = 0.0.0.0
801+listen-port = 2160
802+magic-uuid = 182ad942-6cdd-4a6d-9bc9-5e00190efa6b
803+ssl = False
804+
805+[MattermostBot]
806+bot_url = %(MM_PD_BOT_URL)s
807+bot_team = %(MM_PD_BOT_TEAM)s
808+bot_login =
809+bot_password =
810+bot_token = %(MM_PD_BOT_TOKEN)s
811+ssl_verify = False
812+plugins = modules
813+
814+[nickname to email]
815+jdoe = john.doe@canonical.com
816+
817+# List of Mattermost nick and their aliases
818+[Mattermost Aliases]
819+
820+# List of PagerDuty service ID and the public channel to write to
821+# Default to the public-channel in the PagerDuty section
822+[PagerDuty service to Mattermost Channel]
823+
824+```
825+
826+```
827+juju deploy ./charm-k8s-mm-pd-bot/mm-pd-bot.charm \
828+ --config image_path=rocks.canonical.com/mm-pd-bot:devel \
829+ --config mm_pd_bot_cfg="@bot.cfg" \ # Don't forget the double quotes here
830+ --config juju-external-hostname=mm-pd-bot.local \
831+ --config kubernetes-ingress-allow-http=true \
832+ mm-pd-bot
833+juju wait
834+juju status
835+juju expose mm-pd-bot
836+```
837diff --git a/config.yaml b/config.yaml
838index 6b3d4e3..86224b8 100644
839--- a/config.yaml
840+++ b/config.yaml
841@@ -1,33 +1,38 @@
842 options:
843- mm_pd_bot_image_path:
844- type: string
845- description: |
846- The location of the image to use, e.g. "registry.example.com/mm-pd-bot:v1".
847+ image_path:
848+ type: string
849+ description: |
850+ The location of the image to use, e.g. "registry.example.com/mm-pd-bot:v1".
851
852- This setting is required.
853- default: ''
854- mm_pd_bot_image_username:
855- type: string
856- description: |
857- The username for accessing the registry specified in mm_pd_bot_image_path.
858- default: ''
859- mm_pd_bot_image_password:
860- type: string
861- description: |
862- The password associated with mm_pd_bot_image_username for accessing the registry specified in mm_pd_bot_image_path.
863- default: ''
864- debug:
865- type: string
866- description: |
867- The logging level of the mm-pd-bot application
868- default: 'INFO'
869- mattermost_api_url:
870- type: string
871- description: |
872- The API url of the MatterMost deployment
873- This is required
874- default: ''
875- mattermost_token:
876- type: string
877- description: |
878- The token used to authenticate the bot
879+ This setting is required.
880+ default: ''
881+ image_username:
882+ type: string
883+ description: |
884+ The username for accessing the registry specified in mm_pd_bot_image_path.
885+ default: ''
886+ image_password:
887+ type: string
888+ description: |
889+ The password associated with mm_pd_bot_image_username for accessing the registry specified in mm_pd_bot_image_path.
890+ default: ''
891+ mm_pd_bot_cfg:
892+ type: string
893+ description: |
894+ The whole configuration file of the bot is passed as content to this setting.
895+
896+ This setting is required.
897+ tls_secret_name:
898+ type: string
899+ description: |
900+ The name of the Kubernetes secret to be associated with the ingress resource.
901+
902+ This setting is ignored unless juju-external-hostname begins with "https://".
903+ default: ''
904+ ingress_whitelist_source_range:
905+ type: string
906+ description: |
907+ A comma-separated list of CIDRs to store in the ingress.kubernetes.io/whitelist-source-range annotation.
908+
909+ This can be used to lock down access to Mattermost PagerDuty Bot based on source IP address.
910+ default: ''
911diff --git a/examples/bot.cfg b/examples/bot.cfg
912new file mode 100644
913index 0000000..6de4430
914--- /dev/null
915+++ b/examples/bot.cfg
916@@ -0,0 +1,48 @@
917+# This file is the configuration of the mm-pd-bot
918+# Any value can be interpolated from environment variable as long as they start with MM_PD_BOT
919+# e.g.
920+# bot_url = %(MM_PD_BOT_URL)s
921+
922+
923+[PagerDuty]
924+account = %(MM_PD_BOT_PD_ACCOUNT)s
925+api-token = %(MM_PD_BOT_PD_TOKEN)s
926+private-channel = is-pagerduty
927+public-channel = is-outage
928+filter-status-on-policy = ^(IS 24x7|On Call)$
929+
930+[Prometheus]
931+max_cache_size = 100
932+
933+[httpd]
934+# This parameter will be used for the ingress value and is required
935+hostname = %(MM_PD_BOT_HOSTNAME)s
936+listen-ip = 0.0.0.0
937+listen-port = 2160
938+magic-uuid = 182ad942-6cdd-4a6d-9bc9-5e00190efa6b
939+ssl = False
940+ssl_cert = ssl/is-pd-bot.crt
941+ssl_key = ssl/is-pd-bot.key
942+
943+[nickname to email]
944+jdoe = john.doe@canonical.com
945+
946+# Mattermost mmpy_bot section
947+# Either pick login/password or token
948+# Each parameter is a lowercase name seen at https://github.com/attzonko/mmpy_bot/blob/master/mmpy_bot/settings.py
949+[MattermostBot]
950+bot_url = %(MM_PD_BOT_URL)s
951+bot_team = Canonical
952+bot_login =
953+bot_password =
954+bot_token = %(MM_PD_BOT_TOKEN)s
955+ssl_verify = False
956+plugins = modules
957+
958+# List of Mattermost nick and their aliases
959+[Mattermost Aliases]
960+
961+# List of PagerDuty service ID and the public channel to write to
962+# Default to the public-channel in the PagerDuty section
963+[PagerDuty service to Mattermost Channel]
964+
965diff --git a/requirements.txt b/requirements.txt
966new file mode 100644
967index 0000000..2d81d3b
968--- /dev/null
969+++ b/requirements.txt
970@@ -0,0 +1 @@
971+ops
972diff --git a/src/charm.py b/src/charm.py
973old mode 100644
974new mode 100755
975index eabe60f..a746657
976--- a/src/charm.py
977+++ b/src/charm.py
978@@ -1,28 +1,38 @@
979-"""toto."""
980+#!/usr/bin/env python3
981+
982+# Copyright 2020 Canonical Ltd.
983+# Licensed under the GPLv3, see LICENCE file for details.
984+
985+import configparser
986 import logging
987+from urllib.parse import urlparse
988
989-from ops.charm import (
990- CharmBase,
991- CharmEvents,
992-)
993-from ops.framework import (
994- EventBase,
995- EventSource,
996-)
997+from ops.charm import CharmBase
998 from ops.main import main
999 from ops.model import (
1000 ActiveStatus,
1001 BlockedStatus,
1002 MaintenanceStatus,
1003- WaitingStatus,
1004 )
1005
1006
1007 logger = logging.getLogger()
1008
1009+REQUIRED_JUJU_SETTINGS = ['image_path', 'mm_pd_bot_cfg']
1010+REQUIRED_CFG_SETTINGS = {
1011+ 'PagerDuty': ['account', 'api-token', 'private-channel', 'public-channel'],
1012+ 'Prometheus': ['max_cache_size'],
1013+ 'httpd': ['hostname', 'listen-ip', 'listen-port', 'magic-uuid'],
1014+ 'MattermostBot': ['bot_url', 'bot_team'],
1015+ # Those sections can be empty
1016+ 'nickname to email': [],
1017+ 'Mattermost Aliases': [],
1018+ 'PagerDuty service to Mattermost Channel': [],
1019+}
1020+BOT_CFG_SECTION = 'MattermostBot'
1021
1022-class MmPdBotK8sCharm(CharmBase):
1023
1024+class MmPdBotK8sCharm(CharmBase):
1025 def __init__(self, *args):
1026 super().__init__(*args)
1027
1028@@ -31,44 +41,163 @@ class MmPdBotK8sCharm(CharmBase):
1029 self.framework.observe(self.on.leader_elected, self.configure_pod)
1030 self.framework.observe(self.on.upgrade_charm, self.configure_pod)
1031
1032+ self.bot_config = configparser.ConfigParser(allow_no_value=True)
1033+
1034+ def _check_mm_pd_bot_configuration(self) -> list:
1035+ """Check the configuration part related to mm_pd_bot configuration.
1036+
1037+ :returns: List of errors detected
1038+ :rtype: list
1039+ """
1040+
1041+ errors = []
1042+ try:
1043+ self.bot_config.read_string(self.model.config['mm_pd_bot_cfg'])
1044+ except configparser.Error:
1045+ err_msg = "Error while parsing mm_pd_bot_cfg setting"
1046+ errors.append(err_msg)
1047+ logger.error(err_msg)
1048+ return errors
1049+
1050+ for section, options in REQUIRED_CFG_SETTINGS.items():
1051+ if not self.bot_config.has_section(section):
1052+ err_msg = "Mandatory section {0} missing in bot configuration file".format(section)
1053+ errors.append(err_msg)
1054+ logger.error(err_msg)
1055+ for option in options:
1056+ if not self.bot_config.has_option(section, option):
1057+ err_msg = "Mandatory option {0} missing in section {1}".format(option, section)
1058+ errors.append(err_msg)
1059+ logger.error(err_msg)
1060+ # You need either a token or a login and password to connect to Mattermost bot account.
1061+ bot_token = self.bot_config.get('MattermostBot', 'bot_token', fallback=None)
1062+ bot_login = self.bot_config.get('MattermostBot', 'bot_login', fallback=None)
1063+ bot_password = self.bot_config.get('MattermostBot', 'bot_password', fallback=None)
1064+
1065+ if bot_token is None and (bot_login is None or bot_password is None):
1066+ err_msg = "You need either bot_token or bot_login/bot_password in MattermostBot section"
1067+ errors.append(err_msg)
1068+ logger.error(err_msg)
1069+ return errors
1070+
1071 def _check_for_config_problems(self):
1072- """Sanitize options."""
1073- return "There is a problem."
1074+ """Check that the mandatory configuration items are all set."""
1075+
1076+ config = self.model.config
1077+ errors = []
1078+ for required in REQUIRED_JUJU_SETTINGS:
1079+ if required not in config:
1080+ err_msg = "Mandatory setting {0} missing".format(required)
1081+ errors.append(err_msg)
1082+ logger.error(err_msg)
1083+ # Pointless to go further
1084+ if errors:
1085+ return ", ".join(errors)
1086+
1087+ errors.extend(self._check_mm_pd_bot_configuration())
1088+
1089+ return ", ".join(errors)
1090
1091 def _make_pod_config(self):
1092 """Return an envConfig with some core configuration."""
1093 config = self.model.config
1094 pod_config = {
1095- 'MM_API_URL': config['mattermost_api_url'],
1096- 'MM_PD_BOT_TOKEN': config['mm_pd_bot_token'],
1097- 'MM_PD_BOT_DEBUG': 'DEBUG' if config['debug'] else 'INFO',
1098+ 'MM_PD_BOT_CFG': config['mm_pd_bot_cfg'],
1099 }
1100
1101 return pod_config
1102
1103+ def _update_pod_spec_for_k8s_ingress(self, pod_spec):
1104+ """Add resources to pod_spec configuring site ingress, if needed."""
1105+
1106+ hostname = self.bot_config.get('httpd', 'hostname')
1107+ container_port = self.bot_config.getint('httpd', 'listen-port')
1108+ magic_uuid = self.bot_config.get('httpd', 'magic-uuid')
1109+ ssl = self.bot_config.getboolean('httpd', 'ssl', fallback=False)
1110+
1111+ if ssl:
1112+ scheme = "https"
1113+ else:
1114+ scheme = "http"
1115+
1116+ bot_listening_url = "{0}://{1}:{2}/{3}/".format(scheme, hostname, container_port, magic_uuid)
1117+ logger.debug("The bot will listen on %s", bot_listening_url)
1118+ bot_listening_url_parsed = urlparse(bot_listening_url)
1119+
1120+ if not bot_listening_url_parsed.scheme.startswith('http'):
1121+ logger.error("\"bot_url\" does not start with http, skipping ingress resource creation")
1122+ return
1123+
1124+ annotations = {}
1125+ ingress = {
1126+ "name": "{}-ingress".format(self.app.name),
1127+ "spec": {
1128+ "rules": [
1129+ {
1130+ "host": bot_listening_url_parsed.hostname,
1131+ "http": {
1132+ "paths": [
1133+ {
1134+ "path": "/{0}/".format(magic_uuid),
1135+ "backend": {"serviceName": self.app.name, "servicePort": container_port},
1136+ }
1137+ ]
1138+ },
1139+ }
1140+ ]
1141+ },
1142+ }
1143+ if bot_listening_url_parsed.scheme == 'https':
1144+ ingress['spec']['tls'] = [{'hosts': [bot_listening_url_parsed.hostname]}]
1145+ tls_secret_name = self.model.config['tls_secret_name']
1146+ if tls_secret_name:
1147+ ingress['spec']['tls'][0]['secretName'] = tls_secret_name
1148+ else:
1149+ annotations['nginx.ingress.kubernetes.io/ssl-redirect'] = 'false'
1150+
1151+ ingress_whitelist_source_range = self.model.config['ingress_whitelist_source_range']
1152+ if ingress_whitelist_source_range:
1153+ annotations['nginx.ingress.kubernetes.io/whitelist-source-range'] = ingress_whitelist_source_range
1154+
1155+ if annotations:
1156+ ingress['annotations'] = annotations
1157+
1158+ # Due to https://github.com/canonical/operator/issues/293 we
1159+ # can't use pod.set_spec's k8s_resources argument.
1160+ resources = pod_spec.get('kubernetesResources', {})
1161+ resources['ingressResources'] = [ingress]
1162+ pod_spec['kubernetesResources'] = resources
1163+
1164 def _make_pod_spec(self):
1165 """Return a pod spec with some core configuration."""
1166+
1167 config = self.model.config
1168- mm_pd_bot_image_details = {
1169- 'imagePath': config['mm_pd_bot_image_path'],
1170+ logger.debug("CONFIG: %s", config)
1171+ container_port = self.bot_config.getint('httpd', 'listen-port')
1172+ # magic_uuid = self.bot_config.get('httpd', 'magic-uuid')
1173+ image_details = {
1174+ 'imagePath': config['image_path'],
1175 }
1176- if config['mm_pd_bot_image_username']:
1177- mm_pd_bot_image_details.update(
1178- {'username': config['mm_pd_bot_image_username'], 'password': config['mm_pd_bot_image_password']}
1179- )
1180+ if config['image_username']:
1181+ image_details.update({'username': config['image_username'], 'password': config['image_password']})
1182 pod_config = self._make_pod_config()
1183
1184+ logger.debug("Returning pod spec")
1185+
1186 return {
1187 'version': 3, # otherwise resources are ignored
1188 'containers': [
1189 {
1190 'name': self.app.name,
1191- 'imageDetails': mm_pd_bot_image_details,
1192- 'ports': [{'containerPort': CONTAINER_PORT, 'protocol': 'TCP'}],
1193+ 'imageDetails': image_details,
1194+ # TODO: remove that later on
1195+ 'imagePullPolicy': 'Always',
1196+ 'ports': [{'containerPort': container_port, 'protocol': 'TCP'}],
1197 'envConfig': pod_config,
1198- 'kubernetes': {
1199- 'readinessProbe': {'httpGet': {'path': '/api/v4/system/ping', 'port': CONTAINER_PORT}},
1200- },
1201+ # TODO: Add readiness probe in the bot.
1202+ # 'kubernetes': {
1203+ # 'readinessProbe': {'httpGet': {'path': '/{0}/'.format(magic_uuid), 'port': container_port}},
1204+ # },
1205 }
1206 ],
1207 }
1208@@ -87,11 +216,13 @@ class MmPdBotK8sCharm(CharmBase):
1209
1210 self.unit.status = MaintenanceStatus('Assembling pod spec')
1211 pod_spec = self._make_pod_spec()
1212+ self._update_pod_spec_for_k8s_ingress(pod_spec)
1213
1214 self.unit.status = MaintenanceStatus('Setting pod spec')
1215+ logging.debug("PODSPEC: %s", pod_spec)
1216 self.model.pod.set_spec(pod_spec)
1217 self.unit.status = ActiveStatus()
1218
1219
1220 if __name__ == '__main__':
1221- main(MmPdBotK8sCharm)
1222+ main(MmPdBotK8sCharm, use_juju_for_storage=True)

Subscribers

People subscribed via source and target branches