diff --git a/simple_nopasswd_ns/README b/simple_nopasswd_ns/README new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simple_nopasswd_ns/icons/osm.png b/simple_nopasswd_ns/icons/osm.png new file mode 100644 index 0000000000000000000000000000000000000000..62012d2a2b491bdcd536d62c3c3c863c0d8c1b33 Binary files /dev/null and b/simple_nopasswd_ns/icons/osm.png differ diff --git a/simple_nopasswd_ns/simple_nopasswd_nsd.yaml b/simple_nopasswd_ns/simple_nopasswd_nsd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a9bf29eea394ab30c8f04bd9c9350cac121dd0ee --- /dev/null +++ b/simple_nopasswd_ns/simple_nopasswd_nsd.yaml @@ -0,0 +1,39 @@ +nsd:nsd-catalog: + nsd: + - id: simple_nopasswd-ns + name: simple_nopasswd-ns + short-name: simple_nopasswd-ns + description: NS with 2 VNFs simple_nopasswd-vnf connected by datanet and mgmtnet VLs + version: '1.0' + logo: osm.png + constituent-vnfd: + - vnfd-id-ref: simple_nopasswd-vnf + member-vnf-index: '1' + # - vnfd-id-ref: hackfest-simplecharm-vnf + # member-vnf-index: '2' + vld: + - id: mgmtnet + name: mgmtnet + short-name: mgmtnet + type: ELAN + mgmt-network: 'true' + vim-network-name: mgmt + vnfd-connection-point-ref: + - vnfd-id-ref: simple_nopasswd-vnf + member-vnf-index-ref: '1' + vnfd-connection-point-ref: vnf-mgmt + # - vnfd-id-ref: hackfest-simplecharm-vnf + # member-vnf-index-ref: '2' + # vnfd-connection-point-ref: vnf-mgmt + - id: datanet + name: datanet + short-name: datanet + type: ELAN + vnfd-connection-point-ref: + - vnfd-id-ref: simple_nopasswd-vnf + member-vnf-index-ref: '1' + vnfd-connection-point-ref: vnf-data + # - vnfd-id-ref: hackfest-simplecharm-vnf + # member-vnf-index-ref: '2' + # vnfd-connection-point-ref: vnf-data + diff --git a/simple_nopasswd_vnf/README b/simple_nopasswd_vnf/README new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simple_nopasswd_vnf/charms/simple/LICENSE b/simple_nopasswd_vnf/charms/simple/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/simple_nopasswd_vnf/charms/simple/Makefile b/simple_nopasswd_vnf/charms/simple/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..a1ad3a5cd27751144f6bd1a0a7db50f1e11b18eb --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/Makefile @@ -0,0 +1,24 @@ +#!/usr/bin/make + +all: lint unit_test + + +.PHONY: clean +clean: + @rm -rf .tox + +.PHONY: apt_prereqs +apt_prereqs: + @# Need tox, but don't install the apt version unless we have to (don't want to conflict with pip) + @which tox >/dev/null || (sudo apt-get install -y python-pip && sudo pip install tox) + +.PHONY: lint +lint: apt_prereqs + @tox --notest + @PATH=.tox/py34/bin:.tox/py35/bin flake8 $(wildcard hooks reactive lib unit_tests tests) + @charm proof + +.PHONY: unit_test +unit_test: apt_prereqs + @echo Starting tests... + tox diff --git a/simple_nopasswd_vnf/charms/simple/README.md b/simple_nopasswd_vnf/charms/simple/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f9d6eedf1f0fbda384f38b1bbfd9666717acfdf6 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/README.md @@ -0,0 +1,53 @@ +# Overview + +This is an example charm as demonstrated in the OSM [Hackfest](https://osm.etsi.org/wikipub/index.php/OSM_workshops_and_events) series. + +This is intended to provide a well-documented example of the proxy charm written by Hackfest participants. + +# Prerequisites + +There are two ways that you can exercise this charm: install the latest stable release of OSM or use Juju directly. + +The workshop materials and tutorials cover using charms as part of OSM. You can follow that approach, but this README will focus on using Juju directly. We highly recommend that vendors and charm developers use this approach for the initial development of the charm. + +## Ubuntu 16.04 or higher + +We recommend using Ubuntu 16.04 or higher for the development and testing of charms. It is assumed that you have installed Ubuntu either on physical hardware or in a Virtual Machine. + +## Install LXD and Juju + +We will be installing the required software via snap. Snaps are containerised software packages, preferred because they are easy to create and install, will automatically update to the latest stable version, and contain bundled dependencies. + +``` +snap install lxd +snap install juju +snap install charm +``` + +# Usage + + +## Known Limitations and Issues + +This not only helps users but gives people a place to start if they want to help +you add features to your charm. + +# Configuration + +The configuration options will be listed on the charm store, however If you're +making assumptions or opinionated decisions in the charm (like setting a default +administrator password), you should detail that here so the user knows how to +change it immediately, etc. + +# Contact Information + +## Upstream Project Name + + - Upstream website + - Upstream bug tracker + - Upstream mailing list or contact information + - Feel free to add things if it's useful for users + + +[service]: http://example.com +[icon guidelines]: https://jujucharms.com/docs/stable/authors-charm-icon diff --git a/simple_nopasswd_vnf/charms/simple/actions.yaml b/simple_nopasswd_vnf/charms/simple/actions.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9a73c5676b27fc7c948e538034bed04ec5562656 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/actions.yaml @@ -0,0 +1,62 @@ +## +# Copyright 2016 Canonical Ltd. +# All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +## + +"run": + "description": "Run an arbitrary command" + "params": + "command": + "description": "The command to execute." + "type": "string" + "default": "" + "required": + - "command" +"generate-ssh-key": + "description": "Generate a new SSH keypair for this unit. This will replace any\ + \ existing previously generated keypair." +"verify-ssh-credentials": + "description": "Verify that this unit can authenticate with server specified by\ + \ ssh-hostname and ssh-username." +"get-ssh-public-key": + "description": "Get the public SSH key for this unit." +"start": + "description": "Stop the service on the VNF." +"stop": + "description": "Stop the service on the VNF." +"restart": + "description": "Stop the service on the VNF." +"reboot": + "description": "Reboot the VNF virtual machine." +"upgrade": + "description": "Upgrade the software on the VNF." +"touch": + "description": "Touch a file on the VNF." + "params": + "filename": + "description": "The name of the file to touch." + "type": "string" + "default": "" + "required": + - "filename" +"test": + "description": "Test" + "params": + "region": + "description": "The region." + "type": "string" + "default": "" + "required": + - "region" diff --git a/simple_nopasswd_vnf/charms/simple/actions/generate-ssh-key b/simple_nopasswd_vnf/charms/simple/actions/generate-ssh-key new file mode 100644 index 0000000000000000000000000000000000000000..7e30af4cfa084120a9343bf71c421b69ec3f2967 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/actions/generate-ssh-key @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +## +# Copyright 2016 Canonical Ltd. +# All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +## +import sys +sys.path.append('lib') + +from charms.reactive import main, set_flag +from charmhelpers.core.hookenv import action_fail, action_name + +""" +`set_state` only works here because it's flushed to disk inside the `main()` +loop. remove_state will need to be called inside the action method. +""" +set_flag('actions.{}'.format(action_name())) + +try: + main() +except Exception as e: + action_fail(repr(e)) diff --git a/simple_nopasswd_vnf/charms/simple/actions/get-ssh-public-key b/simple_nopasswd_vnf/charms/simple/actions/get-ssh-public-key new file mode 100644 index 0000000000000000000000000000000000000000..7e30af4cfa084120a9343bf71c421b69ec3f2967 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/actions/get-ssh-public-key @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +## +# Copyright 2016 Canonical Ltd. +# All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +## +import sys +sys.path.append('lib') + +from charms.reactive import main, set_flag +from charmhelpers.core.hookenv import action_fail, action_name + +""" +`set_state` only works here because it's flushed to disk inside the `main()` +loop. remove_state will need to be called inside the action method. +""" +set_flag('actions.{}'.format(action_name())) + +try: + main() +except Exception as e: + action_fail(repr(e)) diff --git a/simple_nopasswd_vnf/charms/simple/actions/reboot b/simple_nopasswd_vnf/charms/simple/actions/reboot new file mode 100644 index 0000000000000000000000000000000000000000..9a2ba24b9efdfa3d21457469c503c050196fb170 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/actions/reboot @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +import sys +sys.path.append('lib') +from charms.reactive import main, set_flag +from charmhelpers.core.hookenv import action_fail, action_name + +set_flag('actions.{}'.format(action_name())) + +try: + main() +except Exception as e: + action_fail(repr(e)) diff --git a/simple_nopasswd_vnf/charms/simple/actions/restart b/simple_nopasswd_vnf/charms/simple/actions/restart new file mode 100644 index 0000000000000000000000000000000000000000..9a2ba24b9efdfa3d21457469c503c050196fb170 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/actions/restart @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +import sys +sys.path.append('lib') +from charms.reactive import main, set_flag +from charmhelpers.core.hookenv import action_fail, action_name + +set_flag('actions.{}'.format(action_name())) + +try: + main() +except Exception as e: + action_fail(repr(e)) diff --git a/simple_nopasswd_vnf/charms/simple/actions/run b/simple_nopasswd_vnf/charms/simple/actions/run new file mode 100644 index 0000000000000000000000000000000000000000..7e30af4cfa084120a9343bf71c421b69ec3f2967 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/actions/run @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +## +# Copyright 2016 Canonical Ltd. +# All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +## +import sys +sys.path.append('lib') + +from charms.reactive import main, set_flag +from charmhelpers.core.hookenv import action_fail, action_name + +""" +`set_state` only works here because it's flushed to disk inside the `main()` +loop. remove_state will need to be called inside the action method. +""" +set_flag('actions.{}'.format(action_name())) + +try: + main() +except Exception as e: + action_fail(repr(e)) diff --git a/simple_nopasswd_vnf/charms/simple/actions/start b/simple_nopasswd_vnf/charms/simple/actions/start new file mode 100644 index 0000000000000000000000000000000000000000..9a2ba24b9efdfa3d21457469c503c050196fb170 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/actions/start @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +import sys +sys.path.append('lib') +from charms.reactive import main, set_flag +from charmhelpers.core.hookenv import action_fail, action_name + +set_flag('actions.{}'.format(action_name())) + +try: + main() +except Exception as e: + action_fail(repr(e)) diff --git a/simple_nopasswd_vnf/charms/simple/actions/stop b/simple_nopasswd_vnf/charms/simple/actions/stop new file mode 100644 index 0000000000000000000000000000000000000000..9a2ba24b9efdfa3d21457469c503c050196fb170 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/actions/stop @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +import sys +sys.path.append('lib') +from charms.reactive import main, set_flag +from charmhelpers.core.hookenv import action_fail, action_name + +set_flag('actions.{}'.format(action_name())) + +try: + main() +except Exception as e: + action_fail(repr(e)) diff --git a/simple_nopasswd_vnf/charms/simple/actions/test b/simple_nopasswd_vnf/charms/simple/actions/test new file mode 100644 index 0000000000000000000000000000000000000000..7e30af4cfa084120a9343bf71c421b69ec3f2967 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/actions/test @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +## +# Copyright 2016 Canonical Ltd. +# All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +## +import sys +sys.path.append('lib') + +from charms.reactive import main, set_flag +from charmhelpers.core.hookenv import action_fail, action_name + +""" +`set_state` only works here because it's flushed to disk inside the `main()` +loop. remove_state will need to be called inside the action method. +""" +set_flag('actions.{}'.format(action_name())) + +try: + main() +except Exception as e: + action_fail(repr(e)) diff --git a/simple_nopasswd_vnf/charms/simple/actions/touch b/simple_nopasswd_vnf/charms/simple/actions/touch new file mode 100644 index 0000000000000000000000000000000000000000..7e30af4cfa084120a9343bf71c421b69ec3f2967 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/actions/touch @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +## +# Copyright 2016 Canonical Ltd. +# All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +## +import sys +sys.path.append('lib') + +from charms.reactive import main, set_flag +from charmhelpers.core.hookenv import action_fail, action_name + +""" +`set_state` only works here because it's flushed to disk inside the `main()` +loop. remove_state will need to be called inside the action method. +""" +set_flag('actions.{}'.format(action_name())) + +try: + main() +except Exception as e: + action_fail(repr(e)) diff --git a/simple_nopasswd_vnf/charms/simple/actions/upgrade b/simple_nopasswd_vnf/charms/simple/actions/upgrade new file mode 100644 index 0000000000000000000000000000000000000000..9a2ba24b9efdfa3d21457469c503c050196fb170 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/actions/upgrade @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +import sys +sys.path.append('lib') +from charms.reactive import main, set_flag +from charmhelpers.core.hookenv import action_fail, action_name + +set_flag('actions.{}'.format(action_name())) + +try: + main() +except Exception as e: + action_fail(repr(e)) diff --git a/simple_nopasswd_vnf/charms/simple/actions/verify-ssh-credentials b/simple_nopasswd_vnf/charms/simple/actions/verify-ssh-credentials new file mode 100644 index 0000000000000000000000000000000000000000..7e30af4cfa084120a9343bf71c421b69ec3f2967 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/actions/verify-ssh-credentials @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +## +# Copyright 2016 Canonical Ltd. +# All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +## +import sys +sys.path.append('lib') + +from charms.reactive import main, set_flag +from charmhelpers.core.hookenv import action_fail, action_name + +""" +`set_state` only works here because it's flushed to disk inside the `main()` +loop. remove_state will need to be called inside the action method. +""" +set_flag('actions.{}'.format(action_name())) + +try: + main() +except Exception as e: + action_fail(repr(e)) diff --git a/simple_nopasswd_vnf/charms/simple/bin/charm-env b/simple_nopasswd_vnf/charms/simple/bin/charm-env new file mode 100644 index 0000000000000000000000000000000000000000..c2adc7fbff30d0e062603cc13a1ae30ad05a092b --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/bin/charm-env @@ -0,0 +1,98 @@ +#!/bin/bash + +find_charm_dirs() { + # Hopefully, $JUJU_CHARM_DIR is set so which venv to use in unambiguous. + if [[ -n "$JUJU_CHARM_DIR" || -n "$CHARM_DIR" ]]; then + if [[ -z "$JUJU_CHARM_DIR" ]]; then + # accept $CHARM_DIR to be more forgiving + export JUJU_CHARM_DIR="$CHARM_DIR" + fi + if [[ -z "$CHARM_DIR" ]]; then + # set CHARM_DIR as well to help with backwards compatibility + export CHARM_DIR="$JUJU_CHARM_DIR" + fi + return + fi + # Try to guess the value for JUJU_CHARM_DIR by looking for a non-subordinate + # (because there's got to be at least one principle) charm directory; + # if there are several, pick the first by alpha order. + agents_dir="/var/lib/juju/agents" + if [[ -d "$agents_dir" ]]; then + desired_charm="$1" + found_charm_dir="" + if [[ -n "$desired_charm" ]]; then + for charm_dir in $(/bin/ls -d "$agents_dir"/unit-*/charm); do + charm_name="$(JUJU_CHARM_DIR="$charm_dir" charm-env python3 -c 'from charmhelpers.core.hookenv import charm_name; print(charm_name())')" + if [[ "$charm_name" == "$desired_charm" ]]; then + if [[ -n "$found_charm_dir" ]]; then + >&2 echo "Ambiguous possibilities for JUJU_CHARM_DIR matching '$desired_charm'; please run within a Juju hook context" + exit 1 + fi + found_charm_dir="$charm_dir" + fi + done + if [[ -z "$found_charm_dir" ]]; then + >&2 echo "Unable to determine JUJU_CHARM_DIR matching '$desired_charm'; please run within a Juju hook context" + exit 1 + fi + export JUJU_CHARM_DIR="$found_charm_dir" + export CHARM_DIR="$found_charm_dir" + return + fi + # shellcheck disable=SC2126 + non_subordinates="$(grep -L 'subordinate:.*true' "$agents_dir"/unit-*/charm/metadata.yaml | wc -l)" + if [[ "$non_subordinates" -gt 1 ]]; then + >&2 echo 'Ambiguous possibilities for JUJU_CHARM_DIR; please use --charm or run within a Juju hook context' + exit 1 + elif [[ "$non_subordinates" -eq 1 ]]; then + for charm_dir in $(/bin/ls -d "$agents_dir"/unit-*/charm); do + if grep -q 'subordinate:.*true' "$charm_dir/metadata.yaml"; then + continue + fi + export JUJU_CHARM_DIR="$charm_dir" + export CHARM_DIR="$charm_dir" + return + done + fi + fi + >&2 echo 'Unable to determine JUJU_CHARM_DIR; please run within a Juju hook context' + exit 1 +} + +try_activate_venv() { + if [[ -d "$JUJU_CHARM_DIR/../.venv" ]]; then + . "$JUJU_CHARM_DIR/../.venv/bin/activate" + fi +} + +find_wrapped() { + PATH="${PATH/\/usr\/local\/sbin:}" which "$(basename "$0")" +} + + +# allow --charm option to hint which JUJU_CHARM_DIR to choose when ambiguous +# NB: --charm option must come first +# NB: option must be processed outside find_charm_dirs to modify $@ +charm_name="" +if [[ "$1" == "--charm" ]]; then + charm_name="$2" + shift; shift +fi + +find_charm_dirs "$charm_name" +try_activate_venv +export PYTHONPATH="$JUJU_CHARM_DIR/lib:$PYTHONPATH" + +if [[ "$(basename "$0")" == "charm-env" ]]; then + # being used as a shebang + exec "$@" +elif [[ "$0" == "$BASH_SOURCE" ]]; then + # being invoked as a symlink wrapping something to find in the venv + exec "$(find_wrapped)" "$@" +elif [[ "$(basename "$BASH_SOURCE")" == "charm-env" ]]; then + # being sourced directly; do nothing + /bin/true +else + # being sourced for wrapped bash helpers + . "$(find_wrapped)" +fi diff --git a/simple_nopasswd_vnf/charms/simple/bin/layer_option b/simple_nopasswd_vnf/charms/simple/bin/layer_option new file mode 100644 index 0000000000000000000000000000000000000000..3253ef8aadb95807f26e5ebd8486adde67e5cbc2 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/bin/layer_option @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 + +import sys +import argparse +from charms import layer + + +parser = argparse.ArgumentParser(description='Access layer options.') +parser.add_argument('section', + help='the section, or layer, the option is from') +parser.add_argument('option', + help='the option to access') + +args = parser.parse_args() +value = layer.options.get(args.section, args.option) +if isinstance(value, bool): + sys.exit(0 if value else 1) +elif isinstance(value, list): + for val in value: + print(val) +else: + print(value) diff --git a/simple_nopasswd_vnf/charms/simple/config.yaml b/simple_nopasswd_vnf/charms/simple/config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..737c37887e357e118ce0d083bb3c726a1c7abb30 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/config.yaml @@ -0,0 +1,42 @@ +"options": + "ssh-hostname": + "type": "string" + "default": "" + "description": "The hostname or IP address of the machine to" + "ssh-username": + "type": "string" + "default": "" + "description": "The username to login as." + "ssh-password": + "type": "string" + "default": "" + "description": "The password used to authenticate." + "ssh-private-key": + "type": "string" + "default": "" + "description": "DEPRECATED. The private ssh key to be used to authenticate." + "ssh-public-key": + "type": "string" + "default": "" + "description": "The public key of this unit." + "ssh-key-type": + "type": "string" + "default": "rsa" + "description": "The type of encryption to use for the SSH key." + "ssh-key-bits": + "type": "int" + "default": !!int "4096" + "description": "The number of bits to use for the SSH key." + "string-option": + "type": "string" + "default": "Default Value" + "description": "A short description of the configuration option" + "boolean-option": + "type": "boolean" + "default": !!bool "false" + "description": "A short description of the configuration option" + "int-option": + "type": "int" + "default": !!int "9001" + "description": "A short description of the configuration option" + diff --git a/simple_nopasswd_vnf/charms/simple/copyright b/simple_nopasswd_vnf/charms/simple/copyright new file mode 100644 index 0000000000000000000000000000000000000000..d4fdd18281c632d030a301d26d45b4dabdb308ef --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/copyright @@ -0,0 +1,16 @@ +Format: http://dep.debian.net/deps/dep5/ + +Files: * +Copyright: Copyright 2015-2017, Canonical Ltd., All Rights Reserved. +License: Apache License 2.0 + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + . + http://www.apache.org/licenses/LICENSE-2.0 + . + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/simple_nopasswd_vnf/charms/simple/copyright.layer-options b/simple_nopasswd_vnf/charms/simple/copyright.layer-options new file mode 100644 index 0000000000000000000000000000000000000000..d4fdd18281c632d030a301d26d45b4dabdb308ef --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/copyright.layer-options @@ -0,0 +1,16 @@ +Format: http://dep.debian.net/deps/dep5/ + +Files: * +Copyright: Copyright 2015-2017, Canonical Ltd., All Rights Reserved. +License: Apache License 2.0 + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + . + http://www.apache.org/licenses/LICENSE-2.0 + . + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/simple_nopasswd_vnf/charms/simple/hooks/collect-metrics b/simple_nopasswd_vnf/charms/simple/hooks/collect-metrics new file mode 100644 index 0000000000000000000000000000000000000000..ed69a2e98c7606eac29ddc80ad02e04fb2a6addb --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/hooks/collect-metrics @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Handle the collect-metrics hook via proxy. + +The normal metrics layer will only execute metrics collection against the local +machine. This hook implements the same approach, but runs the collection code +against the configured ssh proxy. + +Because the metrics hook runs in a restricted context, it can't be run as a +normal reactive event, nor can it access things like config. +""" + +import os +import shlex +from subprocess import check_call, CalledProcessError +import sys +import yaml + +# Load modules from $CHARM_DIR/lib +sys.path.append('lib') +import charms.sshproxy + + +def build_command(doc): + """Build the commands to report metrics. + + Build a list of `add-metric` commands to report the current metrics + back to the Juju controller. + """ + values = {} + metrics = doc.get("metrics", {}) + for metric, mdoc in metrics.items(): + cmd = mdoc.get("command") + if cmd: + try: + value, err = charms.sshproxy._run( + # The command may contain quotes that need to be preserved, + # i.e., `awk '{print $1}' /proc/uptime` + shlex.split(cmd, posix=False) + ) + except Exception as e: + # Ignore all errors + with open("metrics.log", "a") as f: + f.write("{}".format(e)) + continue + + value = value.strip() + if value: + values[metric] = value + + if not values: + return None + command = ["add-metric"] + for metric, value in values.items(): + command.append("%s=%s" % (metric, value)) + return command + + +if __name__ == '__main__': + charm_dir = os.path.dirname(os.path.abspath(os.path.join(__file__, ".."))) + metrics_yaml = os.path.join(charm_dir, "metrics.yaml") + with open(metrics_yaml) as f: + doc = yaml.load(f) + command = build_command(doc) + if command: + check_call(command) diff --git a/simple_nopasswd_vnf/charms/simple/hooks/config-changed b/simple_nopasswd_vnf/charms/simple/hooks/config-changed new file mode 100644 index 0000000000000000000000000000000000000000..9858c6be15b8a682778ab4727835151e1b693801 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/hooks/config-changed @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 + +# Load modules from $JUJU_CHARM_DIR/lib +import sys +sys.path.append('lib') + +from charms.layer import basic # noqa +basic.bootstrap_charm_deps() + +from charmhelpers.core import hookenv # noqa +hookenv.atstart(basic.init_config_states) +hookenv.atexit(basic.clear_config_states) + + +# This will load and run the appropriate @hook and other decorated +# handlers from $JUJU_CHARM_DIR/reactive, $JUJU_CHARM_DIR/hooks/reactive, +# and $JUJU_CHARM_DIR/hooks/relations. +# +# See https://jujucharms.com/docs/stable/authors-charm-building +# for more information on this pattern. +from charms.reactive import main # noqa +main() diff --git a/simple_nopasswd_vnf/charms/simple/hooks/hook.template b/simple_nopasswd_vnf/charms/simple/hooks/hook.template new file mode 100644 index 0000000000000000000000000000000000000000..9858c6be15b8a682778ab4727835151e1b693801 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/hooks/hook.template @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 + +# Load modules from $JUJU_CHARM_DIR/lib +import sys +sys.path.append('lib') + +from charms.layer import basic # noqa +basic.bootstrap_charm_deps() + +from charmhelpers.core import hookenv # noqa +hookenv.atstart(basic.init_config_states) +hookenv.atexit(basic.clear_config_states) + + +# This will load and run the appropriate @hook and other decorated +# handlers from $JUJU_CHARM_DIR/reactive, $JUJU_CHARM_DIR/hooks/reactive, +# and $JUJU_CHARM_DIR/hooks/relations. +# +# See https://jujucharms.com/docs/stable/authors-charm-building +# for more information on this pattern. +from charms.reactive import main # noqa +main() diff --git a/simple_nopasswd_vnf/charms/simple/hooks/install b/simple_nopasswd_vnf/charms/simple/hooks/install new file mode 100644 index 0000000000000000000000000000000000000000..9858c6be15b8a682778ab4727835151e1b693801 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/hooks/install @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 + +# Load modules from $JUJU_CHARM_DIR/lib +import sys +sys.path.append('lib') + +from charms.layer import basic # noqa +basic.bootstrap_charm_deps() + +from charmhelpers.core import hookenv # noqa +hookenv.atstart(basic.init_config_states) +hookenv.atexit(basic.clear_config_states) + + +# This will load and run the appropriate @hook and other decorated +# handlers from $JUJU_CHARM_DIR/reactive, $JUJU_CHARM_DIR/hooks/reactive, +# and $JUJU_CHARM_DIR/hooks/relations. +# +# See https://jujucharms.com/docs/stable/authors-charm-building +# for more information on this pattern. +from charms.reactive import main # noqa +main() diff --git a/simple_nopasswd_vnf/charms/simple/hooks/leader-elected b/simple_nopasswd_vnf/charms/simple/hooks/leader-elected new file mode 100644 index 0000000000000000000000000000000000000000..9858c6be15b8a682778ab4727835151e1b693801 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/hooks/leader-elected @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 + +# Load modules from $JUJU_CHARM_DIR/lib +import sys +sys.path.append('lib') + +from charms.layer import basic # noqa +basic.bootstrap_charm_deps() + +from charmhelpers.core import hookenv # noqa +hookenv.atstart(basic.init_config_states) +hookenv.atexit(basic.clear_config_states) + + +# This will load and run the appropriate @hook and other decorated +# handlers from $JUJU_CHARM_DIR/reactive, $JUJU_CHARM_DIR/hooks/reactive, +# and $JUJU_CHARM_DIR/hooks/relations. +# +# See https://jujucharms.com/docs/stable/authors-charm-building +# for more information on this pattern. +from charms.reactive import main # noqa +main() diff --git a/simple_nopasswd_vnf/charms/simple/hooks/leader-settings-changed b/simple_nopasswd_vnf/charms/simple/hooks/leader-settings-changed new file mode 100644 index 0000000000000000000000000000000000000000..9858c6be15b8a682778ab4727835151e1b693801 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/hooks/leader-settings-changed @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 + +# Load modules from $JUJU_CHARM_DIR/lib +import sys +sys.path.append('lib') + +from charms.layer import basic # noqa +basic.bootstrap_charm_deps() + +from charmhelpers.core import hookenv # noqa +hookenv.atstart(basic.init_config_states) +hookenv.atexit(basic.clear_config_states) + + +# This will load and run the appropriate @hook and other decorated +# handlers from $JUJU_CHARM_DIR/reactive, $JUJU_CHARM_DIR/hooks/reactive, +# and $JUJU_CHARM_DIR/hooks/relations. +# +# See https://jujucharms.com/docs/stable/authors-charm-building +# for more information on this pattern. +from charms.reactive import main # noqa +main() diff --git a/simple_nopasswd_vnf/charms/simple/hooks/post-series-upgrade b/simple_nopasswd_vnf/charms/simple/hooks/post-series-upgrade new file mode 100644 index 0000000000000000000000000000000000000000..9858c6be15b8a682778ab4727835151e1b693801 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/hooks/post-series-upgrade @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 + +# Load modules from $JUJU_CHARM_DIR/lib +import sys +sys.path.append('lib') + +from charms.layer import basic # noqa +basic.bootstrap_charm_deps() + +from charmhelpers.core import hookenv # noqa +hookenv.atstart(basic.init_config_states) +hookenv.atexit(basic.clear_config_states) + + +# This will load and run the appropriate @hook and other decorated +# handlers from $JUJU_CHARM_DIR/reactive, $JUJU_CHARM_DIR/hooks/reactive, +# and $JUJU_CHARM_DIR/hooks/relations. +# +# See https://jujucharms.com/docs/stable/authors-charm-building +# for more information on this pattern. +from charms.reactive import main # noqa +main() diff --git a/simple_nopasswd_vnf/charms/simple/hooks/pre-series-upgrade b/simple_nopasswd_vnf/charms/simple/hooks/pre-series-upgrade new file mode 100644 index 0000000000000000000000000000000000000000..9858c6be15b8a682778ab4727835151e1b693801 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/hooks/pre-series-upgrade @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 + +# Load modules from $JUJU_CHARM_DIR/lib +import sys +sys.path.append('lib') + +from charms.layer import basic # noqa +basic.bootstrap_charm_deps() + +from charmhelpers.core import hookenv # noqa +hookenv.atstart(basic.init_config_states) +hookenv.atexit(basic.clear_config_states) + + +# This will load and run the appropriate @hook and other decorated +# handlers from $JUJU_CHARM_DIR/reactive, $JUJU_CHARM_DIR/hooks/reactive, +# and $JUJU_CHARM_DIR/hooks/relations. +# +# See https://jujucharms.com/docs/stable/authors-charm-building +# for more information on this pattern. +from charms.reactive import main # noqa +main() diff --git a/simple_nopasswd_vnf/charms/simple/hooks/start b/simple_nopasswd_vnf/charms/simple/hooks/start new file mode 100644 index 0000000000000000000000000000000000000000..9858c6be15b8a682778ab4727835151e1b693801 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/hooks/start @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 + +# Load modules from $JUJU_CHARM_DIR/lib +import sys +sys.path.append('lib') + +from charms.layer import basic # noqa +basic.bootstrap_charm_deps() + +from charmhelpers.core import hookenv # noqa +hookenv.atstart(basic.init_config_states) +hookenv.atexit(basic.clear_config_states) + + +# This will load and run the appropriate @hook and other decorated +# handlers from $JUJU_CHARM_DIR/reactive, $JUJU_CHARM_DIR/hooks/reactive, +# and $JUJU_CHARM_DIR/hooks/relations. +# +# See https://jujucharms.com/docs/stable/authors-charm-building +# for more information on this pattern. +from charms.reactive import main # noqa +main() diff --git a/simple_nopasswd_vnf/charms/simple/hooks/stop b/simple_nopasswd_vnf/charms/simple/hooks/stop new file mode 100644 index 0000000000000000000000000000000000000000..9858c6be15b8a682778ab4727835151e1b693801 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/hooks/stop @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 + +# Load modules from $JUJU_CHARM_DIR/lib +import sys +sys.path.append('lib') + +from charms.layer import basic # noqa +basic.bootstrap_charm_deps() + +from charmhelpers.core import hookenv # noqa +hookenv.atstart(basic.init_config_states) +hookenv.atexit(basic.clear_config_states) + + +# This will load and run the appropriate @hook and other decorated +# handlers from $JUJU_CHARM_DIR/reactive, $JUJU_CHARM_DIR/hooks/reactive, +# and $JUJU_CHARM_DIR/hooks/relations. +# +# See https://jujucharms.com/docs/stable/authors-charm-building +# for more information on this pattern. +from charms.reactive import main # noqa +main() diff --git a/simple_nopasswd_vnf/charms/simple/hooks/update-status b/simple_nopasswd_vnf/charms/simple/hooks/update-status new file mode 100644 index 0000000000000000000000000000000000000000..9858c6be15b8a682778ab4727835151e1b693801 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/hooks/update-status @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 + +# Load modules from $JUJU_CHARM_DIR/lib +import sys +sys.path.append('lib') + +from charms.layer import basic # noqa +basic.bootstrap_charm_deps() + +from charmhelpers.core import hookenv # noqa +hookenv.atstart(basic.init_config_states) +hookenv.atexit(basic.clear_config_states) + + +# This will load and run the appropriate @hook and other decorated +# handlers from $JUJU_CHARM_DIR/reactive, $JUJU_CHARM_DIR/hooks/reactive, +# and $JUJU_CHARM_DIR/hooks/relations. +# +# See https://jujucharms.com/docs/stable/authors-charm-building +# for more information on this pattern. +from charms.reactive import main # noqa +main() diff --git a/simple_nopasswd_vnf/charms/simple/hooks/upgrade-charm b/simple_nopasswd_vnf/charms/simple/hooks/upgrade-charm new file mode 100644 index 0000000000000000000000000000000000000000..9858c6be15b8a682778ab4727835151e1b693801 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/hooks/upgrade-charm @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 + +# Load modules from $JUJU_CHARM_DIR/lib +import sys +sys.path.append('lib') + +from charms.layer import basic # noqa +basic.bootstrap_charm_deps() + +from charmhelpers.core import hookenv # noqa +hookenv.atstart(basic.init_config_states) +hookenv.atexit(basic.clear_config_states) + + +# This will load and run the appropriate @hook and other decorated +# handlers from $JUJU_CHARM_DIR/reactive, $JUJU_CHARM_DIR/hooks/reactive, +# and $JUJU_CHARM_DIR/hooks/relations. +# +# See https://jujucharms.com/docs/stable/authors-charm-building +# for more information on this pattern. +from charms.reactive import main # noqa +main() diff --git a/simple_nopasswd_vnf/charms/simple/icon.svg b/simple_nopasswd_vnf/charms/simple/icon.svg new file mode 100644 index 0000000000000000000000000000000000000000..96a5d0c068d4b3271c7e397f76cf77fdf0651038 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/icon.svg @@ -0,0 +1,279 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + diff --git a/simple_nopasswd_vnf/charms/simple/layer.yaml b/simple_nopasswd_vnf/charms/simple/layer.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4c041d477542d6225766c503096fc08bf1be2f14 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/layer.yaml @@ -0,0 +1,15 @@ +"includes": +- "layer:options" +- "layer:basic" +- "layer:sshproxy" +- "layer:vnfproxy" +"options": + "basic": + "use_venv": !!bool "false" + "packages": [] + "python_packages": [] + "include_system_packages": !!bool "true" + "sshproxy": {} + "vnfproxy": {} + "simple": {} +"is": "simple" diff --git a/simple_nopasswd_vnf/charms/simple/lib/charms/layer/__init__.py b/simple_nopasswd_vnf/charms/simple/lib/charms/layer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a8e0c640642f44cac85df60f3d9b7f73b0bb18bb --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/lib/charms/layer/__init__.py @@ -0,0 +1,60 @@ +import sys +from importlib import import_module +from pathlib import Path + + +def import_layer_libs(): + """ + Ensure that all layer libraries are imported. + + This makes it possible to do the following: + + from charms import layer + + layer.foo.do_foo_thing() + + Note: This function must be called after bootstrap. + """ + for module_file in Path('lib/charms/layer').glob('*'): + module_name = module_file.stem + if module_name in ('__init__', 'basic', 'execd') or not ( + module_file.suffix == '.py' or module_file.is_dir() + ): + continue + import_module('charms.layer.{}'.format(module_name)) + + +# Terrible hack to support the old terrible interface. +# Try to get people to call layer.options.get() instead so +# that we can remove this garbage. +# Cribbed from https://stackoverfLow.com/a/48100440/4941864 +class OptionsBackwardsCompatibilityHack(sys.modules[__name__].__class__): + def __call__(self, section=None, layer_file=None): + if layer_file is None: + return self.get(section=section) + else: + return self.get(section=section, + layer_file=Path(layer_file)) + + +def patch_options_interface(): + from charms.layer import options + if sys.version_info.minor >= 5: + options.__class__ = OptionsBackwardsCompatibilityHack + else: + # Py 3.4 doesn't support changing the __class__, so we have to do it + # another way. The last line is needed because we already have a + # reference that doesn't get updated with sys.modules. + name = options.__name__ + hack = OptionsBackwardsCompatibilityHack(name) + hack.get = options.get + sys.modules[name] = hack + sys.modules[__name__].options = hack + + +try: + patch_options_interface() +except ImportError: + # This may fail if pyyaml hasn't been installed yet. But in that + # case, the bootstrap logic will try it again once it has. + pass diff --git a/simple_nopasswd_vnf/charms/simple/lib/charms/layer/basic.py b/simple_nopasswd_vnf/charms/simple/lib/charms/layer/basic.py new file mode 100644 index 0000000000000000000000000000000000000000..1a6ea9fc620de16c0eb13113158aacc241317aab --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/lib/charms/layer/basic.py @@ -0,0 +1,259 @@ +import os +import sys +import shutil +from glob import glob +from subprocess import check_call, CalledProcessError +from time import sleep + +from charms import layer +from charms.layer.execd import execd_preinstall + + +def lsb_release(): + """Return /etc/lsb-release in a dict""" + d = {} + with open('/etc/lsb-release', 'r') as lsb: + for l in lsb: + k, v = l.split('=') + d[k.strip()] = v.strip() + return d + + +def bootstrap_charm_deps(): + """ + Set up the base charm dependencies so that the reactive system can run. + """ + # execd must happen first, before any attempt to install packages or + # access the network, because sites use this hook to do bespoke + # configuration and install secrets so the rest of this bootstrap + # and the charm itself can actually succeed. This call does nothing + # unless the operator has created and populated $JUJU_CHARM_DIR/exec.d. + execd_preinstall() + # ensure that $JUJU_CHARM_DIR/bin is on the path, for helper scripts + charm_dir = os.environ['JUJU_CHARM_DIR'] + os.environ['PATH'] += ':%s' % os.path.join(charm_dir, 'bin') + venv = os.path.abspath('../.venv') + vbin = os.path.join(venv, 'bin') + vpip = os.path.join(vbin, 'pip') + vpy = os.path.join(vbin, 'python') + hook_name = os.path.basename(sys.argv[0]) + is_bootstrapped = os.path.exists('wheelhouse/.bootstrapped') + is_charm_upgrade = hook_name == 'upgrade-charm' + is_series_upgrade = hook_name == 'post-series-upgrade' + post_upgrade = os.path.exists('wheelhouse/.upgrade') + is_upgrade = not post_upgrade and (is_charm_upgrade or is_series_upgrade) + if is_bootstrapped and not is_upgrade: + activate_venv() + # the .upgrade file prevents us from getting stuck in a loop + # when re-execing to activate the venv; at this point, we've + # activated the venv, so it's safe to clear it + if post_upgrade: + os.unlink('wheelhouse/.upgrade') + return + if is_series_upgrade and os.path.exists(venv): + # series upgrade should do a full clear of the venv, rather than just + # updating it, to bring in updates to Python itself + shutil.rmtree(venv) + if is_upgrade: + if os.path.exists('wheelhouse/.bootstrapped'): + os.unlink('wheelhouse/.bootstrapped') + open('wheelhouse/.upgrade', 'w').close() + # bootstrap wheelhouse + if os.path.exists('wheelhouse'): + with open('/root/.pydistutils.cfg', 'w') as fp: + # make sure that easy_install also only uses the wheelhouse + # (see https://github.com/pypa/pip/issues/410) + fp.writelines([ + "[easy_install]\n", + "allow_hosts = ''\n", + "find_links = file://{}/wheelhouse/\n".format(charm_dir), + ]) + apt_install([ + 'python3-pip', + 'python3-setuptools', + 'python3-yaml', + 'python3-dev', + 'python3-wheel', + 'build-essential', + ]) + from charms.layer import options + cfg = options.get('basic') + # include packages defined in layer.yaml + apt_install(cfg.get('packages', [])) + # if we're using a venv, set it up + if cfg.get('use_venv'): + if not os.path.exists(venv): + series = lsb_release()['DISTRIB_CODENAME'] + if series in ('precise', 'trusty'): + apt_install(['python-virtualenv']) + else: + apt_install(['virtualenv']) + cmd = ['virtualenv', '-ppython3', '--never-download', venv] + if cfg.get('include_system_packages'): + cmd.append('--system-site-packages') + check_call(cmd) + os.environ['PATH'] = ':'.join([vbin, os.environ['PATH']]) + pip = vpip + else: + pip = 'pip3' + # save a copy of system pip to prevent `pip3 install -U pip` + # from changing it + if os.path.exists('/usr/bin/pip'): + shutil.copy2('/usr/bin/pip', '/usr/bin/pip.save') + # need newer pip, to fix spurious Double Requirement error: + # https://github.com/pypa/pip/issues/56 + check_call([pip, 'install', '-U', '--no-index', '-f', 'wheelhouse', + 'pip']) + # per https://github.com/juju-solutions/layer-basic/issues/110 + # this replaces the setuptools that was copied over from the system on + # venv create with latest setuptools and adds setuptools_scm + check_call([pip, 'install', '-U', '--no-index', '-f', 'wheelhouse', + 'setuptools', 'setuptools-scm']) + # install the rest of the wheelhouse deps + check_call([pip, 'install', '-U', '--no-index', '-f', 'wheelhouse'] + + glob('wheelhouse/*')) + # re-enable installation from pypi + os.remove('/root/.pydistutils.cfg') + # install python packages from layer options + if cfg.get('python_packages'): + check_call([pip, 'install', '-U'] + cfg.get('python_packages')) + if not cfg.get('use_venv'): + # restore system pip to prevent `pip3 install -U pip` + # from changing it + if os.path.exists('/usr/bin/pip.save'): + shutil.copy2('/usr/bin/pip.save', '/usr/bin/pip') + os.remove('/usr/bin/pip.save') + # setup wrappers to ensure envs are used for scripts + shutil.copy2('bin/charm-env', '/usr/local/sbin/') + for wrapper in ('charms.reactive', 'charms.reactive.sh', + 'chlp', 'layer_option'): + src = os.path.join('/usr/local/sbin', 'charm-env') + dst = os.path.join('/usr/local/sbin', wrapper) + if not os.path.exists(dst): + os.symlink(src, dst) + if cfg.get('use_venv'): + shutil.copy2('bin/layer_option', vbin) + else: + shutil.copy2('bin/layer_option', '/usr/local/bin/') + # re-link the charm copy to the wrapper in case charms + # call bin/layer_option directly (as was the old pattern) + os.remove('bin/layer_option') + os.symlink('/usr/local/sbin/layer_option', 'bin/layer_option') + # flag us as having already bootstrapped so we don't do it again + open('wheelhouse/.bootstrapped', 'w').close() + # Ensure that the newly bootstrapped libs are available. + # Note: this only seems to be an issue with namespace packages. + # Non-namespace-package libs (e.g., charmhelpers) are available + # without having to reload the interpreter. :/ + reload_interpreter(vpy if cfg.get('use_venv') else sys.argv[0]) + + +def activate_venv(): + """ + Activate the venv if enabled in ``layer.yaml``. + + This is handled automatically for normal hooks, but actions might + need to invoke this manually, using something like: + + # Load modules from $JUJU_CHARM_DIR/lib + import sys + sys.path.append('lib') + + from charms.layer.basic import activate_venv + activate_venv() + + This will ensure that modules installed in the charm's + virtual environment are available to the action. + """ + from charms.layer import options + venv = os.path.abspath('../.venv') + vbin = os.path.join(venv, 'bin') + vpy = os.path.join(vbin, 'python') + use_venv = options.get('basic', 'use_venv') + if use_venv and '.venv' not in sys.executable: + # activate the venv + os.environ['PATH'] = ':'.join([vbin, os.environ['PATH']]) + reload_interpreter(vpy) + layer.patch_options_interface() + layer.import_layer_libs() + + +def reload_interpreter(python): + """ + Reload the python interpreter to ensure that all deps are available. + + Newly installed modules in namespace packages sometimes seemt to + not be picked up by Python 3. + """ + os.execve(python, [python] + list(sys.argv), os.environ) + + +def apt_install(packages): + """ + Install apt packages. + + This ensures a consistent set of options that are often missed but + should really be set. + """ + if isinstance(packages, (str, bytes)): + packages = [packages] + + env = os.environ.copy() + + if 'DEBIAN_FRONTEND' not in env: + env['DEBIAN_FRONTEND'] = 'noninteractive' + + cmd = ['apt-get', + '--option=Dpkg::Options::=--force-confold', + '--assume-yes', + 'install'] + for attempt in range(3): + try: + check_call(cmd + packages, env=env) + except CalledProcessError: + if attempt == 2: # third attempt + raise + try: + # sometimes apt-get update needs to be run + check_call(['apt-get', 'update']) + except CalledProcessError: + # sometimes it's a dpkg lock issue + pass + sleep(5) + else: + break + + +def init_config_states(): + import yaml + from charmhelpers.core import hookenv + from charms.reactive import set_state + from charms.reactive import toggle_state + config = hookenv.config() + config_defaults = {} + config_defs = {} + config_yaml = os.path.join(hookenv.charm_dir(), 'config.yaml') + if os.path.exists(config_yaml): + with open(config_yaml) as fp: + config_defs = yaml.safe_load(fp).get('options', {}) + config_defaults = {key: value.get('default') + for key, value in config_defs.items()} + for opt in config_defs.keys(): + if config.changed(opt): + set_state('config.changed') + set_state('config.changed.{}'.format(opt)) + toggle_state('config.set.{}'.format(opt), config.get(opt)) + toggle_state('config.default.{}'.format(opt), + config.get(opt) == config_defaults[opt]) + + +def clear_config_states(): + from charmhelpers.core import hookenv, unitdata + from charms.reactive import remove_state + config = hookenv.config() + remove_state('config.changed') + for opt in config.keys(): + remove_state('config.changed.{}'.format(opt)) + remove_state('config.set.{}'.format(opt)) + remove_state('config.default.{}'.format(opt)) + unitdata.kv().flush() diff --git a/simple_nopasswd_vnf/charms/simple/lib/charms/layer/execd.py b/simple_nopasswd_vnf/charms/simple/lib/charms/layer/execd.py new file mode 100644 index 0000000000000000000000000000000000000000..438d9a1bc90042fd8b20517d5ecf358dfbf08afc --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/lib/charms/layer/execd.py @@ -0,0 +1,114 @@ +# Copyright 2014-2016 Canonical Limited. +# +# This file is part of layer-basic, the reactive base layer for Juju. +# +# charm-helpers is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 3 as +# published by the Free Software Foundation. +# +# charm-helpers is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with charm-helpers. If not, see . + +# This module may only import from the Python standard library. +import os +import sys +import subprocess +import time + +''' +execd/preinstall + +Read the layer-basic docs for more info on how to use this feature. +https://charmsreactive.readthedocs.io/en/latest/layer-basic.html#exec-d-support +''' + + +def default_execd_dir(): + return os.path.join(os.environ['JUJU_CHARM_DIR'], 'exec.d') + + +def execd_module_paths(execd_dir=None): + """Generate a list of full paths to modules within execd_dir.""" + if not execd_dir: + execd_dir = default_execd_dir() + + if not os.path.exists(execd_dir): + return + + for subpath in os.listdir(execd_dir): + module = os.path.join(execd_dir, subpath) + if os.path.isdir(module): + yield module + + +def execd_submodule_paths(command, execd_dir=None): + """Generate a list of full paths to the specified command within exec_dir. + """ + for module_path in execd_module_paths(execd_dir): + path = os.path.join(module_path, command) + if os.access(path, os.X_OK) and os.path.isfile(path): + yield path + + +def execd_sentinel_path(submodule_path): + module_path = os.path.dirname(submodule_path) + execd_path = os.path.dirname(module_path) + module_name = os.path.basename(module_path) + submodule_name = os.path.basename(submodule_path) + return os.path.join(execd_path, + '.{}_{}.done'.format(module_name, submodule_name)) + + +def execd_run(command, execd_dir=None, stop_on_error=True, stderr=None): + """Run command for each module within execd_dir which defines it.""" + if stderr is None: + stderr = sys.stdout + for submodule_path in execd_submodule_paths(command, execd_dir): + # Only run each execd once. We cannot simply run them in the + # install hook, as potentially storage hooks are run before that. + # We cannot rely on them being idempotent. + sentinel = execd_sentinel_path(submodule_path) + if os.path.exists(sentinel): + continue + + try: + subprocess.check_call([submodule_path], stderr=stderr, + universal_newlines=True) + with open(sentinel, 'w') as f: + f.write('{} ran successfully {}\n'.format(submodule_path, + time.ctime())) + f.write('Removing this file will cause it to be run again\n') + except subprocess.CalledProcessError as e: + # Logs get the details. We can't use juju-log, as the + # output may be substantial and exceed command line + # length limits. + print("ERROR ({}) running {}".format(e.returncode, e.cmd), + file=stderr) + print("STDOUT< 0: + raise CalledProcessError(returncode=retcode, + cmd=cmd, + output=stderr.decode("utf-8").strip()) + return (stdout.decode('utf-8').strip(), stderr.decode('utf-8').strip()) + + +def _run(cmd, env=None): + """Run a command remotely via SSH. + + Note: The previous behavior was to run the command locally if SSH wasn't + configured, but that can lead to cases where execution succeeds when you'd + expect it not to. + """ + if isinstance(cmd, str): + cmd = shlex.split(cmd) + + if type(cmd) is not list: + cmd = [cmd] + + cfg = get_config() + + if cfg: + if all(k in cfg for k in ['ssh-hostname', 'ssh-username', + 'ssh-password', 'ssh-private-key']): + host = get_host_ip() + user = cfg['ssh-username'] + passwd = cfg['ssh-password'] + key = cfg['ssh-private-key'] # DEPRECATED + + if host and user: + return ssh(cmd, host, user, passwd, key) + + raise Exception("Invalid SSH credentials.") + + +def get_ssh_client(host, user, password=None, key=None): + """Return a connected Paramiko ssh object.""" + client = paramiko.SSHClient() + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + + pkey = None + + # Check for the DEPRECATED private-key + if key: + f = io.StringIO(key) + pkey = paramiko.RSAKey.from_private_key(f) + else: + # Otherwise, check for the auto-generated private key + if os.path.exists('/root/.ssh/id_juju_sshproxy'): + with open('/root/.ssh/id_juju_sshproxy', 'r') as f: + pkey = paramiko.RSAKey.from_private_key(f) + + ########################################################################### + # There is a bug in some versions of OpenSSH 4.3 (CentOS/RHEL 5) where # + # the server may not send the SSH_MSG_USERAUTH_BANNER message except when # + # responding to an auth_none request. For example, paramiko will attempt # + # to use password authentication when a password is set, but the server # + # could deny that, instead requesting keyboard-interactive. The hack to # + # workaround this is to attempt a reconnect, which will receive the right # + # banner, and authentication can proceed. See the following for more info # + # https://github.com/paramiko/paramiko/issues/432 # + # https://github.com/paramiko/paramiko/pull/438 # + ########################################################################### + + try: + client.connect(host, port=22, username=user, + password=password, pkey=pkey) + except paramiko.ssh_exception.SSHException as e: + if 'Error reading SSH protocol banner' == str(e): + # Once more, with feeling + client.connect(host, port=22, username=user, + password=password, pkey=pkey) + else: + # Reraise the original exception + raise e + + return client + + +def sftp(local_file, remote_file, host, user, password=None, key=None): + """Copy a local file to a remote host.""" + client = get_ssh_client(host, user, password, key) + + # Create an sftp connection from the underlying transport + sftp = paramiko.SFTPClient.from_transport(client.get_transport()) + sftp.put(local_file, remote_file) + client.close() + + +def ssh(cmd, host, user, password=None, key=None): + """Run an arbitrary command over SSH.""" + client = get_ssh_client(host, user, password, key) + + cmds = ' '.join(cmd) + stdin, stdout, stderr = client.exec_command(cmds, get_pty=True) + retcode = stdout.channel.recv_exit_status() + client.close() # @TODO re-use connections + if retcode > 0: + output = stderr.read().strip() + raise CalledProcessError(returncode=retcode, cmd=cmd, + output=output) + return ( + stdout.read().decode('utf-8').strip(), + stderr.read().decode('utf-8').strip() + ) diff --git a/simple_nopasswd_vnf/charms/simple/metadata.yaml b/simple_nopasswd_vnf/charms/simple/metadata.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5f8df59eded85680c5dda1db50a9855dd14c59e8 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/metadata.yaml @@ -0,0 +1,16 @@ +"name": "simple" +"summary": "A simple VNF proxy charm" +"maintainer": "Adam Israel " +"description": | + VNF "proxy" charms are a lightweight version of a charm that, rather than + installing software on the same machine, execute commands over an ssh channel. +"tags": + # Replace "misc" with one or more whitelisted tags from this list: + # https://jujucharms.com/docs/stable/authors-charm-metadata +- "misc" +- "osm" +- "vnf" +"series": +- "xenial" +- "trusty" +"subordinate": !!bool "false" diff --git a/simple_nopasswd_vnf/charms/simple/metrics.yaml b/simple_nopasswd_vnf/charms/simple/metrics.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6ebb605c6fb6bbf011bcbee537c294dea43b20d4 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/metrics.yaml @@ -0,0 +1,5 @@ +metrics: + uptime: + type: gauge + description: "Uptime of the VNF" + command: awk '{print $1}' /proc/uptime diff --git a/simple_nopasswd_vnf/charms/simple/reactive/__init__.py b/simple_nopasswd_vnf/charms/simple/reactive/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simple_nopasswd_vnf/charms/simple/reactive/simple.py b/simple_nopasswd_vnf/charms/simple/reactive/simple.py new file mode 100644 index 0000000000000000000000000000000000000000..3d14a01f22837c08cdab59893eafee11ca3163f1 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/reactive/simple.py @@ -0,0 +1,59 @@ +from charmhelpers.core.hookenv import ( + action_get, + action_fail, + action_set, + status_set, +) +from charms.reactive import ( + clear_flag, + set_flag, + when, + when_not, +) +import charms.sshproxy + + +@when('sshproxy.configured') +@when_not('simple.installed') +def install_simple_proxy_charm(): + """Post-install actions. + + This function will run when two conditions are met: + 1. The 'sshproxy.configured' state is set + 2. The 'simple.installed' state is not set + + This ensures that the workload status is set to active only when the SSH + proxy is properly configured. + """ + set_flag('simple.installed') + status_set('active', 'Ready!') + + +@when('actions.touch') +def touch(): + err = '' + try: + filename = action_get('filename') + cmd = ['touch {}'.format(filename)] + result, err = charms.sshproxy._run(cmd) + except Exception: + action_fail('command failed:' + err) + else: + action_set({'output': result}) + finally: + clear_flag('actions.touch') + +@when('actions.test') +def test(): + err = '' + try: + region = action_get('region') + # cmd = ["yq w -i /home/ubuntu/controllers.yaml controllers.libjuju.region {}".format(region)] + cmd = ['yq', 'w', '-i', '/home/ubuntu/controllers.yaml', 'controllers.libjuju.region', 'us-west-1'] + result, err = charms.sshproxy._run(cmd) + except: + action_fail('command failed:' + err) + else: + action_set({'outout': result}) + finally: + clear_flag('actions.set-apn') \ No newline at end of file diff --git a/simple_nopasswd_vnf/charms/simple/reactive/sshproxy.py b/simple_nopasswd_vnf/charms/simple/reactive/sshproxy.py new file mode 100644 index 0000000000000000000000000000000000000000..cde43bc2193c1c410363d2c81873017d725ad7aa --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/reactive/sshproxy.py @@ -0,0 +1,209 @@ +## +# Copyright 2016 Canonical Ltd. +# All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +## + +from charmhelpers.core import unitdata +from charmhelpers.core.hookenv import ( + action_fail, + action_get, + action_set, + config, + log, + status_set, + DEBUG, +) + +from charms.reactive.flags import register_trigger + +from charms.reactive import ( + clear_flag, + set_flag, + when, + when_not, + when_any, +) +import charms.sshproxy +import os +import subprocess + +# Register a trigger so that we can respond to config.changed, even if +# it's being cleared by another handler +register_trigger(when='config.changed', + set_flag='sshproxy.reconfigure') + + +@when_any('config.changed', 'sshproxy.reconfigure') +def ssh_configured(): + """Check if charm is properly configured. + + Check to see if the charm is configured with SSH credentials. If so, + set a state flag that can be used to execute ssh-only actions. + + For example: + + @when('sshproxy.configured') + def run_remote_command(cmd): + ... + + @when_not('sshproxy.configured') + def run_local_command(cmd): + ... + """ + log("Checking sshproxy configuration", DEBUG) + cfg = config() + ssh_keys = ['ssh-hostname', 'ssh-username', + 'ssh-password', 'ssh-private-key'] + + if all(k in cfg for k in ssh_keys): + + # Store config in unitdata so it's accessible to sshproxy + db = unitdata.kv() + db.set('config', cfg) + + # Explicitly flush the kv so it's immediately available + db.flush() + + log("Verifying ssh credentials...", DEBUG) + (verified, output) = charms.sshproxy.verify_ssh_credentials() + if verified: + log("SSH credentials verified.", DEBUG) + set_flag('sshproxy.configured') + status_set('active', 'Ready!') + else: + clear_flag('sshproxy.configured') + status_set('blocked', "Verification failed: {}".format(output)) + else: + log("No ssh credentials configured", DEBUG) + clear_flag('sshproxy.configured') + status_set('blocked', 'Invalid SSH credentials.') + + +def generate_ssh_key(): + """Generate a new 4096-bit rsa keypair. + + If there is an existing keypair for this unit, it will be overwritten. + """ + cfg = config() + if all(k in cfg for k in ['ssh-key-type', 'ssh-key-bits']): + keytype = cfg['ssh-key-type'] + bits = str(cfg['ssh-key-bits']) + privatekey = '/root/.ssh/id_juju_sshproxy' + publickey = "{}.pub".format(privatekey) + + if os.path.exists(privatekey): + os.remove(privatekey) + if os.path.exists(publickey): + os.remove(publickey) + + cmd = "ssh-keygen -t {} -b {} -N '' -f {}".format( + keytype, + bits, + privatekey + ) + + output, err = charms.sshproxy.run_local([cmd]) + if len(err) == 0: + return True + return False + + +@when('actions.generate-ssh-key') +def action_generate_ssh_key(): + """Generate a new 4096-bit rsa keypair. + + If there is an existing keypair for this unit, it will be overwritten. + """ + try: + if not generate_ssh_key(): + action_fail('Unable to generate ssh key.') + except subprocess.CalledProcessError as e: + action_fail('Command failed: %s (%s)' % + (' '.join(e.cmd), str(e.output))) + finally: + clear_flag('actions.generate-ssh-key') + + +def get_ssh_public_key(): + """Get the public SSH key of this unit.""" + publickey_path = '/root/.ssh/id_juju_sshproxy.pub' + publickey = None + if os.path.exists(publickey_path): + with open(publickey_path, 'r') as f: + publickey = f.read() + + return publickey + + +@when('actions.get-ssh-public-key') +def action_get_ssh_public_key(): + """Get the public SSH key of this unit.""" + try: + action_set({'pubkey': get_ssh_public_key()}) + except subprocess.CalledProcessError as e: + action_fail('Command failed: %s (%s)' % + (' '.join(e.cmd), str(e.output))) + finally: + clear_flag('actions.get-ssh-public-key') + + +@when('actions.verify-ssh-credentials') +def action_verify_ssh_credentials(): + """Verify the ssh credentials have been installed to the VNF. + + Attempts to run a stock command - `hostname` on the remote host. + """ + try: + (verified, output) = charms.sshproxy.verify_ssh_credentials() + action_set({ + 'output': output, + 'verified': verified, + }) + if not verified: + action_fail("Verification failed: {}".format( + output, + )) + finally: + clear_flag('actions.verify-ssh-credentials') + + +@when('actions.run') +def run_command(): + """Run an arbitrary command. + + Run an arbitrary command, either locally or over SSH with the configured + credentials. + """ + try: + cmd = action_get('command') + output, err = charms.sshproxy._run(cmd) + if len(err): + action_fail("Command '{}' returned error code {}".format(cmd, err)) + else: + action_set({'output': output}) + except subprocess.CalledProcessError as e: + action_fail('Command failed: %s (%s)' % + (' '.join(e.cmd), str(e.output))) + finally: + clear_flag('actions.run') + + +@when_not('sshproxy.installed') +def install_vnf_ubuntu_proxy(): + """Install and Configure SSH Proxy.""" + + log("Generating SSH key...", DEBUG) + generate_ssh_key() + set_flag('sshproxy.installed') diff --git a/simple_nopasswd_vnf/charms/simple/reactive/vnfproxy.py b/simple_nopasswd_vnf/charms/simple/reactive/vnfproxy.py new file mode 100644 index 0000000000000000000000000000000000000000..6616991df245a920116b9301b52602f15ba7a9bc --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/reactive/vnfproxy.py @@ -0,0 +1,89 @@ +from charmhelpers.core.hookenv import ( + action_fail, + action_set, +) + +from charms.reactive import ( + when, + clear_flag, +) +import charms.sshproxy + + +@when('actions.reboot') +def reboot(): + err = '' + try: + result, err = charms.sshproxy._run("reboot") + except: + action_fail('command failed:' + err) + else: + action_set({'outout': result}) + finally: + clear_flag('actions.reboot') + + +############################################################################### +# Below is an example implementation of the start/stop/restart actions. # +# To use this, copy the below code into your layer and add the appropriate # +# command(s) necessary to perform the action. # +############################################################################### + +# @when('actions.start') +# def start(): +# err = '' +# try: +# cmd = "service myname start" +# result, err = charms.sshproxy._run(cmd) +# except: +# action_fail('command failed:' + err) +# else: +# action_set({'outout': result}) +# finally: +# clear_flag('actions.start') +# +# +# @when('actions.stop') +# def stop(): +# err = '' +# try: +# # Enter the command to stop your service(s) +# cmd = "service myname stop" +# result, err = charms.sshproxy._run(cmd) +# except: +# action_fail('command failed:' + err) +# else: +# action_set({'outout': result}) +# finally: +# clear_flag('actions.stop') +# +# +# @when('actions.restart') +# def restart(): +# err = '' +# try: +# # Enter the command to restart your service(s) +# cmd = "service myname restart" +# result, err = charms.sshproxy._run(cmd) +# except: +# action_fail('command failed:' + err) +# else: +# action_set({'outout': result}) +# finally: +# clear_flag('actions.restart') +# +# +# @when('actions.upgrade') +# def upgrade_vnf(): +# err = '' +# try: +# # Add the command(s) to perform a VNF software upgrade +# cmd = '' +# result, err = charms.sshproxy._run(cmd) +# except: +# action_fail('command failed:' + err) +# else: +# action_set({'outout': result}) +# finally: +# clear_flag('actions.upgrade') +# diff --git a/simple_nopasswd_vnf/charms/simple/requirements.txt b/simple_nopasswd_vnf/charms/simple/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..28ecacab6029381bd43d65f8dcfc0cc704870f71 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/requirements.txt @@ -0,0 +1,2 @@ +flake8 +pytest diff --git a/simple_nopasswd_vnf/charms/simple/tests/00-setup b/simple_nopasswd_vnf/charms/simple/tests/00-setup new file mode 100644 index 0000000000000000000000000000000000000000..f0616a560a811bae78d7872dd433d612909c73cd --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/tests/00-setup @@ -0,0 +1,5 @@ +#!/bin/bash + +sudo add-apt-repository ppa:juju/stable -y +sudo apt-get update +sudo apt-get install amulet python-requests -y diff --git a/simple_nopasswd_vnf/charms/simple/tests/10-deploy b/simple_nopasswd_vnf/charms/simple/tests/10-deploy new file mode 100644 index 0000000000000000000000000000000000000000..9a26117089498423ebba7dda3f7e3acb50ba54e7 --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/tests/10-deploy @@ -0,0 +1,35 @@ +#!/usr/bin/python3 + +import amulet +import requests +import unittest + + +class TestCharm(unittest.TestCase): + def setUp(self): + self.d = amulet.Deployment() + + self.d.add('simple') + self.d.expose('simple') + + self.d.setup(timeout=900) + self.d.sentry.wait() + + self.unit = self.d.sentry['simple'][0] + + def test_service(self): + # test we can access over http + page = requests.get('http://{}'.format(self.unit.info['public-address'])) + self.assertEqual(page.status_code, 200) + # Now you can use self.d.sentry[SERVICE][UNIT] to address each of the units and perform + # more in-depth steps. Each self.d.sentry[SERVICE][UNIT] has the following methods: + # - .info - An array of the information of that unit from Juju + # - .file(PATH) - Get the details of a file on that unit + # - .file_contents(PATH) - Get plain text output of PATH file from that unit + # - .directory(PATH) - Get details of directory + # - .directory_contents(PATH) - List files and folders in PATH on that unit + # - .relation(relation, service:rel) - Get relation data from return service + + +if __name__ == '__main__': + unittest.main() diff --git a/simple_nopasswd_vnf/charms/simple/tox.ini b/simple_nopasswd_vnf/charms/simple/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..6f0fa11dee3187367ecd1637bef45533f289fd9e --- /dev/null +++ b/simple_nopasswd_vnf/charms/simple/tox.ini @@ -0,0 +1,15 @@ +[tox] +skipsdist=True +envlist = py34, py35 +skip_missing_interpreters = True + +[testenv] +# This is not pretty, but pytest will return 0 if all tests worked and 5 if no tests are found. +# We want to consider no tests as an indication of success. +commands = /bin/bash -c 'py.test -v || if [[ $? == 5 ]]; then true; else false; fi' + +deps = + -r{toxinidir}/requirements.txt + +[flake8] +exclude=docs diff --git a/simple_nopasswd_vnf/charms/simple/wheelhouse/setuptools-39.0.1.zip b/simple_nopasswd_vnf/charms/simple/wheelhouse/setuptools-39.0.1.zip new file mode 100644 index 0000000000000000000000000000000000000000..e4b0aaca167d76e92f2ef499e206799366799017 Binary files /dev/null and b/simple_nopasswd_vnf/charms/simple/wheelhouse/setuptools-39.0.1.zip differ diff --git a/simple_nopasswd_vnf/cloud_init/cloud-config.txt b/simple_nopasswd_vnf/cloud_init/cloud-config.txt new file mode 100644 index 0000000000000000000000000000000000000000..f6c1b9dcf3a0506e7366e58d0318a5df5f2639ce --- /dev/null +++ b/simple_nopasswd_vnf/cloud_init/cloud-config.txt @@ -0,0 +1,13 @@ +#cloud-config +password: osm4u +chpasswd: { expire: False } +ssh_pwauth: True + +write_files: +- content: | + # My new helloworld file + + owner: root:root + permissions: '0644' + path: /root/helloworld.txt + diff --git a/simple_nopasswd_vnf/icons/osm.png b/simple_nopasswd_vnf/icons/osm.png new file mode 100644 index 0000000000000000000000000000000000000000..62012d2a2b491bdcd536d62c3c3c863c0d8c1b33 Binary files /dev/null and b/simple_nopasswd_vnf/icons/osm.png differ diff --git a/simple_nopasswd_vnf/simple_nopasswd_vnfd.yaml b/simple_nopasswd_vnf/simple_nopasswd_vnfd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c4a2696308a1d29be6199a588444ee97990cbfc2 --- /dev/null +++ b/simple_nopasswd_vnf/simple_nopasswd_vnfd.yaml @@ -0,0 +1,108 @@ +vnfd:vnfd-catalog: + vnfd: + - connection-point: + - id: vnf-mgmt + name: vnf-mgmt + short-name: vnf-mgmt + type: VPORT + - id: vnf-data + name: vnf-data + short-name: vnf-data + type: VPORT + description: A VNF consisting of 2 VDUs connected to an internal VL, and one VDU + with cloud-init + id: simple_nopasswd-vnf + internal-vld: + - id: internal + internal-connection-point: + - id-ref: mgmtVM-internal + - id-ref: dataVM-internal + name: internal + short-name: internal + type: ELAN + logo: osm.png + mgmt-interface: + cp: vnf-mgmt + name: simple_nopasswd-vnf + short-name: simple_nopasswd-vnf + vdu: + - cloud-init-file: cloud-config.txt + count: '1' + id: mgmtVM + image: ubuntu16.04 + interface: + - external-connection-point-ref: vnf-mgmt + name: mgmtVM-eth0 + position: '1' + type: EXTERNAL + virtual-interface: + type: PARAVIRT + - internal-connection-point-ref: mgmtVM-internal + name: mgmtVM-eth1 + position: '2' + type: INTERNAL + virtual-interface: + type: PARAVIRT + internal-connection-point: + - id: mgmtVM-internal + name: mgmtVM-internal + short-name: mgmtVM-internal + type: VPORT + name: mgmtVM + vm-flavor: + memory-mb: '1024' + storage-gb: '10' + vcpu-count: '1' + - count: '1' + id: dataVM + image: ubuntu16.04 + interface: + - internal-connection-point-ref: dataVM-internal + name: dataVM-eth0 + position: '1' + type: INTERNAL + virtual-interface: + type: PARAVIRT + - external-connection-point-ref: vnf-data + name: dataVM-xe0 + position: '2' + type: EXTERNAL + virtual-interface: + type: PARAVIRT + internal-connection-point: + - id: dataVM-internal + name: dataVM-internal + short-name: dataVM-internal + type: VPORT + name: dataVM + vm-flavor: + memory-mb: '1024' + storage-gb: '10' + vcpu-count: '1' + version: '1.0' + vnf-configuration: + config-access: + ssh-access: + default-user: ubuntu + required: true + config-primitive: + - name: touch + parameter: + - data-type: STRING + default-value: /home/ubuntu/touched + name: filename + initial-config-primitive: + - name: config + parameter: + - name: ssh-hostname + value: + - name: ssh-username + value: ubuntu + seq: '1' + - name: touch + parameter: + - name: filename + value: /home/ubuntu/first-touch + seq: '2' + juju: + charm: simple diff --git a/ubuntu_cloudinit_ns/README b/ubuntu_cloudinit_ns/README new file mode 100644 index 0000000000000000000000000000000000000000..eeb8e117ba11d728b9825f77976fc7207971d8c3 --- /dev/null +++ b/ubuntu_cloudinit_ns/README @@ -0,0 +1,2 @@ +Descriptor created by OSM descriptor package generated +Created on Mon May 27 13:17:59 UTC 2019 diff --git a/ubuntu_cloudinit_ns/ubuntu_cloudinit_nsd.yaml b/ubuntu_cloudinit_ns/ubuntu_cloudinit_nsd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..56da9c7aef6b716e9acf70596043cbbeb4e5b9e8 --- /dev/null +++ b/ubuntu_cloudinit_ns/ubuntu_cloudinit_nsd.yaml @@ -0,0 +1,26 @@ +nsd:nsd-catalog: + nsd: + - id: ubuntu_cloudinit-ns + name: ubuntu_cloudinit-ns + short-name: ubuntu_cloudinit-ns + description: Generated by OSM package generator + vendor: OSM + version: '1.0' + + + constituent-vnfd: + - member-vnf-index: 1 + vnfd-id-ref: ubuntu_cloudinit-vnf + + vld: + # Networks for the VNFs + - id: mgmtnet + name: mgmtnet + short-name: mgmtnet + type: ELAN + mgmt-network: 'true' + # vim-network-name: + vnfd-connection-point-ref: + - member-vnf-index-ref: 1 + vnfd-id-ref: ubuntu_cloudinit-vnf + vnfd-connection-point-ref: vnf-cp0 diff --git a/ubuntu_cloudinit_vnf/README b/ubuntu_cloudinit_vnf/README new file mode 100644 index 0000000000000000000000000000000000000000..55a357d6ae53865bca7298288735a962fe4d3cad --- /dev/null +++ b/ubuntu_cloudinit_vnf/README @@ -0,0 +1,2 @@ +Descriptor created by OSM descriptor package generated +Created on Mon May 27 13:11:46 UTC 2019 diff --git a/ubuntu_cloudinit_vnf/cloud_init/cloud-init.cfg b/ubuntu_cloudinit_vnf/cloud_init/cloud-init.cfg new file mode 100644 index 0000000000000000000000000000000000000000..fae0cf1a8ec349186a29a2b0ed2373285044d9b8 --- /dev/null +++ b/ubuntu_cloudinit_vnf/cloud_init/cloud-init.cfg @@ -0,0 +1,5 @@ +#cloud-config +password: {{ password }} +chpasswd: { expire: False } +ssh_pwauth: True + diff --git a/ubuntu_cloudinit_vnf/ubuntu_cloudinit_vnfd.yaml b/ubuntu_cloudinit_vnf/ubuntu_cloudinit_vnfd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8136f659e48793f42d64adb22baa43cfbf6e60a3 --- /dev/null +++ b/ubuntu_cloudinit_vnf/ubuntu_cloudinit_vnfd.yaml @@ -0,0 +1,38 @@ +vnfd:vnfd-catalog: + vnfd: + - id: ubuntu_cloudinit-vnf + name: ubuntu_cloudinit-vnf + short-name: ubuntu_cloudinit-vnf + description: Generated by OSM package generator + vendor: OSM + version: '1.0' + + # Management interface + mgmt-interface: + cp: vnf-cp0 + + vdu: + - id: ubuntu_cloudinit-vnf-VM + name: ubuntu_cloudinit-vnf-VM + description: ubuntu_cloudinit-vnf-VM + count: 1 + cloud-init-file: cloud-init.cfg + + vm-flavor: + vcpu-count: 2 + memory-mb: 2048 + storage-gb: 10 + + # Image including the full path + image: 'ubuntu16.04' + + interface: + - name: eth0 + type: EXTERNAL + virtual-interface: + type: PARAVIRT + external-connection-point-ref: vnf-cp0 + + connection-point: + - name: vnf-cp0 +