Commit ab6961e6 authored by garciadeblas's avatar garciadeblas
Browse files

Remove old NF and NS packages already, new versions available at charm-packages


Signed-off-by: garciadeblas's avatargarciadeblas <gerardo.garciadeblas@telefonica.com>
parent 5fedfaf3
Pipeline #7108 failed with stage
in 1 minute and 39 seconds
nsd:
nsd:
- description: NS with 2 VNFs with cloudinit connected by datanet and mgmtnet VLs
df:
- id: default-df
vnf-profile:
- id: vnf1
virtual-link-connectivity:
- constituent-cpd-id:
- constituent-base-element-id: vnf1
constituent-cpd-id: vnf-mgmt-ext
virtual-link-profile-id: mgmtnet
- constituent-cpd-id:
- constituent-base-element-id: vnf1
constituent-cpd-id: vnf-data-ext
virtual-link-profile-id: datanet
vnfd-id: hackfest_k8sproxycharm-vnf
- id: vnf2
virtual-link-connectivity:
- constituent-cpd-id:
- constituent-base-element-id: vnf2
constituent-cpd-id: vnf-mgmt-ext
virtual-link-profile-id: mgmtnet
- constituent-cpd-id:
- constituent-base-element-id: vnf2
constituent-cpd-id: vnf-data-ext
virtual-link-profile-id: datanet
vnfd-id: hackfest_k8sproxycharm-vnf
id: hackfest_k8sproxycharm-ns
name: hackfest_k8sproxycharm-ns
version: 1.0
virtual-link-desc:
- id: mgmtnet
mgmt-network: true
- id: datanet
vnfd-id:
- hackfest_k8sproxycharm-vnf
[submodule "mod/operator"]
path = mod/operator
url = https://github.com/canonical/operator
[submodule "mod/charms.osm"]
path = mod/charms.osm
url = https://github.com/charmed-osm/charms.osm
[submodule "mod/charms"]
path = mod/charms
url = https://github.com/AdamIsrael/charms.requirementstxt
# charm-simple-k8s
This is a WORK IN PROGRESS example of a simple proxy charm used by Open Source Mano (OSM), written in the [Python Operator Framwork](https://github.com/canonical/operator)
## Usage
To get the charm:
```bash
git clone https://github.com/charmed-osm/charm-simple-k8s
cd charm-simple-k8s
# Install the submodules
git submodule update --init
```
To configure the charm, you'll need to have an SSH-accessible machine. You'll need the hostname, and the username and password to login to. Password authentication is useful for testing but key-based authentication is preferred when deploying through OSM.
To deploy to juju:
```
juju deploy . --config ssh-hostname=10.135.22.x --config ssh-username=ubuntu --config ssh-password=ubuntu --resource ubuntu_image=ubuntu/ubuntu:latest
```
```
# Make sure the charm is in an Active state
juju status
```
To test the SSH credentials, run the `verify-ssh-credentials` action and inspect it's output:
```
$ juju run-action simple-k8s/0 verify-ssh-credentials
Action queued with id: "9"
$ juju show-action-output 9
UnitId: simple-k8s/0
results:
Stdout: |
Verified!
verified: "True"
status: completed
timing:
completed: 2020-02-14 19:30:38 +0000 UTC
enqueued: 2020-02-14 19:30:33 +0000 UTC
started: 2020-02-14 19:30:36 +0000 UTC
```
To exercise the charm, run the `touch` function
```
juju run-action simple-k8s/0 touch filename=/home/ubuntu/firsttouch
```
Then ssh to the remote machine and verify that the file has been created.
touch:
description: "Touch a file on the VNF."
params:
filename:
description: "The name of the file to touch."
type: string
default: ""
required:
- filename
# Standard OSM functions
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."
# Required by charms.osm.sshproxy
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."
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: 4096
description: "The number of bits to use for the SSH key."
"""Module to help with executing commands over SSH."""
##
# 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 log
import io
import ipaddress
import paramiko
import os
import socket
import shlex
import traceback
from subprocess import (
check_call,
Popen,
CalledProcessError,
PIPE,
)
class SSHProxy:
private_key_path = "/root/.ssh/id_sshproxy"
public_key_path = "/root/.ssh/id_sshproxy.pub"
key_type = "rsa"
key_bits = 4096
def __init__(self, hostname: str, username: str, password: str = ""):
self.hostname = hostname
self.username = username
self.password = password
@staticmethod
def generate_ssh_key():
"""Generate a 4096-bit rsa keypair."""
if not os.path.exists(SSHProxy.private_key_path):
cmd = "ssh-keygen -t {} -b {} -N '' -f {}".format(
SSHProxy.key_type, SSHProxy.key_bits, SSHProxy.private_key_path,
)
try:
check_call(cmd, shell=True)
except CalledProcessError:
return False
return True
@staticmethod
def get_ssh_public_key():
publickey = ""
if os.path.exists(SSHProxy.private_key_path):
with open(SSHProxy.public_key_path, "r") as f:
publickey = f.read()
return publickey
@staticmethod
def has_ssh_key():
if os.path.exists(SSHProxy.private_key_path):
return True
else:
return False
def run(self, cmd: str) -> (str, str):
"""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)
host = self._get_hostname()
user = self.username
passwd = self.password
key = self.private_key_path
# Make sure we have everything we need to connect
if host and user:
return self._ssh(cmd)
raise Exception("Invalid SSH credentials.")
def sftp(self, local, remote):
client = self._get_ssh_client()
# Create an sftp connection from the underlying transport
sftp = paramiko.SFTPClient.from_transport(client.get_transport())
sftp.put(local_file, remote_file)
client.close()
pass
def verify_credentials(self):
"""Verify the SSH credentials."""
try:
(stdout, stderr) = self.run("hostname")
except CalledProcessError as e:
stderr = "Command failed: {} ({})".format(" ".join(e.cmd), str(e.output))
except paramiko.ssh_exception.AuthenticationException as e:
stderr = "{}.".format(e)
except paramiko.ssh_exception.BadAuthenticationType as e:
stderr = "{}".format(e.explanation)
except paramiko.ssh_exception.BadHostKeyException as e:
stderr = "Host key mismatch: expected {} but got {}.".format(
e.expected_key, e.got_key,
)
except (TimeoutError, socket.timeout):
stderr = "Timeout attempting to reach {}".format(cfg["ssh-hostname"])
except Exception as error:
tb = traceback.format_exc()
stderr = "Unhandled exception: {}".format(tb)
if len(stderr) == 0:
return True, stderr
return False, stderr
###################
# Private methods #
###################
def _get_hostname(self):
"""Get the hostname for the ssh target.
HACK: This function was added to work around an issue where the
ssh-hostname was passed in the format of a.b.c.d;a.b.c.d, where the first
is the floating ip, and the second the non-floating ip, for an Openstack
instance.
"""
return self.hostname.split(";")[0]
def _get_ssh_client(self):
"""Return a connected Paramiko ssh object."""
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
pkey = None
# Otherwise, check for the auto-generated private key
if os.path.exists(self.private_key_path):
with open(self.private_key_path) 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(
self.hostname,
port=22,
username=self.username,
password=self.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 _ssh(self, cmd):
"""Run an arbitrary command over SSH.
Returns a tuple of (stdout, stderr)
"""
client = self._get_ssh_client()
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(),
)
## OLD ##
# def get_config():
# """Get the current charm configuration.
# Get the "live" kv store every time we need to access the charm config, in
# case it has recently been changed by a config-changed event.
# """
# db = unitdata.kv()
# return db.get('config')
# def get_host_ip():
# """Get the IP address for the ssh host.
# HACK: This function was added to work around an issue where the
# ssh-hostname was passed in the format of a.b.c.d;a.b.c.d, where the first
# is the floating ip, and the second the non-floating ip, for an Openstack
# instance.
# """
# cfg = get_config()
# return cfg['ssh-hostname'].split(';')[0]
# def is_valid_hostname(hostname):
# """Validate the ssh-hostname."""
# print("Hostname: {}".format(hostname))
# if hostname == "0.0.0.0":
# return False
# try:
# ipaddress.ip_address(hostname)
# except ValueError:
# return False
# return True
# def verify_ssh_credentials():
# """Verify the ssh credentials have been installed to the VNF.
# Attempts to run a stock command - `hostname` on the remote host.
# """
# verified = False
# status = ''
# cfg = get_config()
# try:
# host = get_host_ip()
# if is_valid_hostname(host):
# if len(cfg['ssh-hostname']) and len(cfg['ssh-username']):
# cmd = 'hostname'
# status, err = _run(cmd)
# if len(err) == 0:
# verified = True
# else:
# status = "Invalid IP address."
# except CalledProcessError as e:
# status = 'Command failed: {} ({})'.format(
# ' '.join(e.cmd),
# str(e.output)
# )
# except paramiko.ssh_exception.AuthenticationException as e:
# status = '{}.'.format(e)
# except paramiko.ssh_exception.BadAuthenticationType as e:
# status = '{}'.format(e.explanation)
# except paramiko.ssh_exception.BadHostKeyException as e:
# status = 'Host key mismatch: expected {} but got {}.'.format(
# e.expected_key,
# e.got_key,
# )
# except (TimeoutError, socket.timeout):
# status = "Timeout attempting to reach {}".format(cfg['ssh-hostname'])
# except Exception as error:
# tb = traceback.format_exc()
# status = 'Unhandled exception: {}'.format(tb)
# return (verified, status)
# def charm_dir():
# """Return the root directory of the current charm."""
# d = os.environ.get('JUJU_CHARM_DIR')
# if d is not None:
# return d
# return os.environ.get('CHARM_DIR')
# def run_local(cmd, env=None):
# """Run a command locally."""
# if isinstance(cmd, str):
# cmd = shlex.split(cmd) if ' ' in cmd else [cmd]
# if type(cmd) is not list:
# cmd = [cmd]
# p = Popen(cmd,
# env=env,
# shell=True,
# stdout=PIPE,
# stderr=PIPE)
# stdout, stderr = p.communicate()
# retcode = p.poll()
# if retcode > 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()
# )
#!/usr/bin/env python3
# Requirements.txt support
import sys
sys.path.append("lib")
from ops.framework import StoredState
import os
import subprocess
import sys
from remote_pdb import RemotePdb
REQUIREMENTS_TXT = "{}/requirements.txt".format(os.environ["JUJU_CHARM_DIR"])
def install_requirements():
if os.path.exists(REQUIREMENTS_TXT):
# First, make sure python3 and python3-pip are installed
if not os.path.exists("/usr/bin/python3") or not os.path.exists("/usr/bin/pip3"):
# Update the apt cache
subprocess.check_call(["apt-get", "update"])
# Install the Python3 package
subprocess.check_call(
["apt-get", "install", "-y", "python3", "python3-pip", "python3-paramiko"],
# Eat stdout so it's not returned in an action's stdout
# TODO: redirect to a file handle and log to juju log
# stdout=subprocess.DEVNULL,
)
# Lastly, install the python requirements
cmd = [sys.executable, "-m", "pip", "install", "-r", REQUIREMENTS_TXT]
# stdout = subprocess.check_output(cmd)
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
stdout, stderr = p.communicate()
print(stdout)
print(stderr)
# subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", REQUIREMENTS_TXT],
# # Eat stdout so it's not returned in an action's stdout
# # TODO: redirect to a file handle and log to juju log
# # stdout=subprocess.DEVNULL,
# )
# Use StoredState to make sure we're run exactly once automatically
# RemotePdb('127.0.0.1', 4444).set_trace()
state = StoredState()
installed = getattr(state, "requirements_txt_installed", None)
if not installed:
install_requirements()
state.requirements_txt_installed = True
# Copyright 2019 Canonical Ltd.
#
# 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 os
import yaml
from ops.framework import Object, EventSource, EventBase, EventsBase
class HookEvent(EventBase):
pass
class ActionEvent(EventBase):
def defer(self):
raise RuntimeError('cannot defer action events')
def restore(self, snapshot):
env_action_name = os.environ.get('JUJU_ACTION_NAME')
event_action_name = self.handle.kind[:-len('_action')].replace('_', '-')
if event_action_name != env_action_name:
# This could only happen if the dev manually emits the action, or from a bug.
raise RuntimeError('action event kind does not match current action')
# Params are loaded at restore rather than __init__ because the model is not available in __init__.
self.params = self.framework.model._backend.action_get()
def set_results(self, results):
self.framework.model._backend.action_set(results)
def log(self, message):
self.framework.model._backend.action_log(message)
def fail(self, message=''):
self.framework.model._backend.action_fail(message)
class InstallEvent(HookEvent):
pass
class StartEvent(HookEvent):
pass
class StopEvent(HookEvent):
pass
class ConfigChangedEvent(HookEvent):
pass
class UpdateStatusEvent(HookEvent):
pass
class UpgradeCharmEvent(HookEvent):
pass
class PreSeriesUpgradeEvent(HookEvent):
pass
class PostSeriesUpgradeEvent(HookEvent):
pass
class LeaderElectedEvent(HookEvent):
pass
class LeaderSettingsChangedEvent(HookEvent):
pass
class RelationEvent(HookEvent):
def __init__(self, handle, relation, app=None, unit=None):
super().__init__(handle)
if unit and unit.app != app:
raise RuntimeError(f'cannot create RelationEvent with application {app} and unit {unit}')
self.relation = relation
self.app = app
self.unit = unit
def snapshot(self):
snapshot = {
'relation_name': self.relation.name,
'relation_id': self.relation.id,
}
if self.app:
snapshot['app_name'] = self.app.name
if self.unit:
snapshot['unit_name'] = self.unit.name
return snapshot
def restore(self, snapshot):
self.relation = self.framework.model.get_relation(snapshot['relation_name'], snapshot['relation_id'])
app_name = snapshot.get('app_name')
if app_name:
self.app = self.framework.model.get_app(app_name)
else:
self.app = None
unit_name = snapshot.get('unit_name')
if unit_name:
self.unit = self.framework.model.get_unit(unit_name)
else:
self.unit = None
class RelationJoinedEvent(RelationEvent):
pass
class RelationChangedEvent(RelationEvent):
pass
class RelationDepartedEvent(RelationEvent):
pass
class RelationBrokenEvent(RelationEvent):
pass
class StorageEvent(HookEvent):
pass
class StorageAttachedEvent(StorageEvent):
pass
class StorageDetachingEvent(StorageEvent):
pass
class CharmEvents(EventsBase):
install = EventSource(InstallEvent)
start = EventSource(StartEvent)
stop = EventSource(StopEvent)
update_status = EventSource(UpdateStatusEvent)
config_changed = EventSource(ConfigChangedEvent)
upgrade_charm = EventSource(UpgradeCharmEvent)
pre_series_upgrade = EventSource(PreSeriesUpgradeEvent)
post_series_upgrade = EventSource(PostSeriesUpgradeEvent)
leader_elected = EventSource(LeaderElectedEvent)
leader_settings_changed = EventSource(LeaderSettingsChangedEvent)
class CharmBase(Object):
on = CharmEvents()
def __init__(self, framework, key):
super().__init__(framework, key)
for relation_name in self.framework.meta.relations:
relation_name = relation_name.replace('-', '_')
self.on.define_event(f'{relation_name}_relation_joined', RelationJoinedEvent)
self.on.define_event(f'{relation_name}_relation_changed', RelationChangedEvent)
self.on.define_event(f'{relation_name}_relation_departed', RelationDepartedEvent)
self.on.define_event(f'{relation_name}_relation_broken', RelationBrokenEvent)
for storage_name in self.framework.meta.storages:
storage_name = storage_name.replace('-', '_')
self.on.define_event(f'{storage_name}_storage_attached', StorageAttachedEvent)
self.on.define_event(f'{storage_name}_storage_detaching', StorageDetachingEvent)
for action_name in self.framework.meta.actions:
action_name = action_name.replace('-', '_')
self.on.define_event(f'{action_name}_action', ActionEvent)
class CharmMeta:
"""Object containing the metadata for the charm.
The maintainers, tags, terms, series, and extra_bindings attributes are all
lists of strings. The requires, provides, peers, relations, storage,
resources, and payloads attributes are all mappings of names to instances
of the respective RelationMeta, StorageMeta, ResourceMeta, or PayloadMeta.
The relations attribute is a convenience accessor which includes all of the
requires, provides, and peers RelationMeta items. If needed, the role of
the relation definition can be obtained from its role attribute.
"""
def __init__(self, raw={}, actions_raw={}):
self.name = raw.get('name', '')
self.summary = raw.get('summary', '')
self.description = raw.get('description', '')
self.maintainers = []
if 'maintainer' in raw:
self.maintainers.append(raw['maintainer'])
if 'maintainers' in raw:
self.maintainers.extend(raw['maintainers'])
self.tags = raw.get('tags', [])
self.terms = raw.get('terms', [])
self.series = raw.get('series', [])
self.subordinate = raw.get('subordinate', False)
self.min_juju_version = raw.get('min-juju-version')
self.requires = {name: RelationMeta('requires', name, rel)
for name, rel in raw.get('requires', {}).items()}
self.provides = {name: RelationMeta('provides', name, rel)
for name, rel in raw.get('provides', {}).items()}
self.peers = {name: RelationMeta('peers', name, rel)
for name, rel in raw.get('peers', {}).items()}
self.relations = {}
self.relations.update(self.requires)
self.relations.update(self.provides)
self.relations.update(self.peers)
self.storages = {name: StorageMeta(name, storage)
for name, storage in raw.get('storage', {}).items()}
self.resources = {name: ResourceMeta(name, res)
for name, res in raw.get('resources', {}).items()}
self.payloads = {name: PayloadMeta(name, payload)
for name, payload in raw.get('payloads', {}).items()}
self.extra_bindings = raw.get('extra-bindings', [])
self.actions = {name: ActionMeta(name, action) for name, action in actions_raw.items()}
@classmethod
def from_yaml(cls, metadata, actions=None):
meta = yaml.safe_load(metadata)
raw_actions = {}
if actions is not None:
raw_actions = yaml.safe_load(actions)
return cls(meta, raw_actions)
class RelationMeta:
"""Object containing metadata about a relation definition."""
def __init__(self, role, relation_name, raw):
self.role = role
self.relation_name = relation_name
self.interface_name = raw['interface']
self.scope = raw.get('scope')
class StorageMeta:
"""Object containing metadata about a storage definition."""
def __init__(self, name, raw):
self.storage_name = name
self.type = raw['type']
self.description = raw.get('description', '')
self.shared = raw.get('shared', False)
self.read_only = raw.get('read-only', False)
self.minimum_size = raw.get('minimum-size')
self.location = raw.get('location')
self.multiple_range = None
if 'multiple' in raw:
range = raw['multiple']['range']
if '-' not in range:
self.multiple_range = (int(range), int(range))
else:
range = range.split('-')
self.multiple_range = (int(range[0]), int(range[1]) if range[1] else None)
class ResourceMeta:
"""Object containing metadata about a resource definition."""
def __init__(self, name, raw):
self.resource_name = name
self.type = raw['type']
self.filename = raw.get('filename', None)
self.description = raw.get('description', '')
class PayloadMeta:
"""Object containing metadata about a payload definition."""
def __init__(self, name, raw):
self.payload_name = name
self.type = raw['type']
class ActionMeta:
def __init__(self, name, raw=None):
raw = raw or {}
self.name = name
self.title = raw.get('title', '')
self.description = raw.get('description', '')
self.parameters = raw.get('params', {}) # {<parameter name>: <JSON Schema definition>}
self.required = raw.get('required', []) # [<parameter name>, ...]
# Copyright 2020 Canonical Ltd.
#
# 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 re
from functools import total_ordering
@total_ordering
class JujuVersion:
PATTERN = r'^(?P<major>\d{1,9})\.(?P<minor>\d{1,9})((?:\.|-(?P<tag>[a-z]+))(?P<patch>\d{1,9}))?(\.(?P<build>\d{1,9}))?$'
def __init__(self, version):
m = re.match(self.PATTERN, version)
if not m:
raise RuntimeError(f'"{version}" is not a valid Juju version string')
d = m.groupdict()
self.major = int(m.group('major'))
self.minor = int(m.group('minor'))
self.tag = d['tag'] or ''
self.patch = int(d['patch'] or 0)
self.build = int(d['build'] or 0)
def __repr__(self):
if self.tag:
s = f'{self.major}.{self.minor}-{self.tag}{self.patch}'
else:
s = f'{self.major}.{self.minor}.{self.patch}'
if self.build > 0:
s += f'.{self.build}'
return s
def __eq__(self, other):
if self is other:
return True
if isinstance(other, str):
other = type(self)(other)
elif not isinstance(other, JujuVersion):
raise RuntimeError(f'cannot compare Juju version "{self}" with "{other}"')
return self.major == other.major and self.minor == other.minor\
and self.tag == other.tag and self.build == other.build and self.patch == other.patch
def __lt__(self, other):
if self is other:
return False
if isinstance(other, str):
other = type(self)(other)
elif not isinstance(other, JujuVersion):
raise RuntimeError(f'cannot compare Juju version "{self}" with "{other}"')
if self.major != other.major:
return self.major < other.major
elif self.minor != other.minor:
return self.minor < other.minor
elif self.tag != other.tag:
if not self.tag:
return False
elif not other.tag:
return True
return self.tag < other.tag
elif self.patch != other.patch:
return self.patch < other.patch
elif self.build != other.build:
return self.build < other.build
return False
#!/usr/bin/env python3
# Copyright 2019 Canonical Ltd.
#
# 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 os
import sys
from pathlib import Path
import yaml
import ops.charm
import ops.framework
import ops.model
CHARM_STATE_FILE = '.unit-state.db'
def debugf(format, *args, **kwargs):
pass
def _get_charm_dir():
charm_dir = os.environ.get("JUJU_CHARM_DIR")
if charm_dir is None:
# Assume $JUJU_CHARM_DIR/lib/op/main.py structure.
charm_dir = Path(f'{__file__}/../../..').resolve()
else:
charm_dir = Path(charm_dir).resolve()
return charm_dir
def _load_metadata(charm_dir):
metadata = yaml.safe_load((charm_dir / 'metadata.yaml').read_text())
actions_meta = charm_dir / 'actions.yaml'
if actions_meta.exists():
actions_metadata = yaml.safe_load(actions_meta.read_text())
else:
actions_metadata = {}
return metadata, actions_metadata
def _create_event_link(charm, bound_event):
"""Create a symlink for a particular event.
charm -- A charm object.
bound_event -- An event for which to create a symlink.
"""
if issubclass(bound_event.event_type, ops.charm.HookEvent):
event_dir = charm.framework.charm_dir / 'hooks'
event_path = event_dir / bound_event.event_kind.replace('_', '-')
elif issubclass(bound_event.event_type, ops.charm.ActionEvent):
if not bound_event.event_kind.endswith("_action"):
raise RuntimeError(f"action event name {bound_event.event_kind} needs _action suffix")
event_dir = charm.framework.charm_dir / 'actions'
# The event_kind is suffixed with "_action" while the executable is not.
event_path = event_dir / bound_event.event_kind[:-len('_action')].replace('_', '-')
else:
raise RuntimeError(f'cannot create a symlink: unsupported event type {bound_event.event_type}')
event_dir.mkdir(exist_ok=True)
if not event_path.exists():
# CPython has different implementations for populating sys.argv[0] for Linux and Windows. For Windows
# it is always an absolute path (any symlinks are resolved) while for Linux it can be a relative path.
target_path = os.path.relpath(os.path.realpath(sys.argv[0]), event_dir)
# Ignore the non-symlink files or directories assuming the charm author knows what they are doing.
debugf(f'Creating a new relative symlink at {event_path} pointing to {target_path}')
event_path.symlink_to(target_path)
def _setup_event_links(charm_dir, charm):
"""Set up links for supported events that originate from Juju.
Whether a charm can handle an event or not can be determined by
introspecting which events are defined on it.
Hooks or actions are created as symlinks to the charm code file which is determined by inspecting
symlinks provided by the charm author at hooks/install or hooks/start.
charm_dir -- A root directory of the charm.
charm -- An instance of the Charm class.
"""
for bound_event in charm.on.events().values():
# Only events that originate from Juju need symlinks.
if issubclass(bound_event.event_type, (ops.charm.HookEvent, ops.charm.ActionEvent)):
_create_event_link(charm, bound_event)
def _emit_charm_event(charm, event_name):
"""Emits a charm event based on a Juju event name.
charm -- A charm instance to emit an event from.
event_name -- A Juju event name to emit on a charm.
"""
event_to_emit = None
try:
event_to_emit = getattr(charm.on, event_name)
except AttributeError:
debugf(f"event {event_name} not defined for {charm}")
# If the event is not supported by the charm implementation, do
# not error out or try to emit it. This is to support rollbacks.
if event_to_emit is not None:
args, kwargs = _get_event_args(charm, event_to_emit)
debugf(f'Emitting Juju event {event_name}')
event_to_emit.emit(*args, **kwargs)
def _get_event_args(charm, bound_event):
event_type = bound_event.event_type
model = charm.framework.model
if issubclass(event_type, ops.charm.RelationEvent):
relation_name = os.environ['JUJU_RELATION']
relation_id = int(os.environ['JUJU_RELATION_ID'].split(':')[-1])
relation = model.get_relation(relation_name, relation_id)
else:
relation = None
remote_app_name = os.environ.get('JUJU_REMOTE_APP', '')
remote_unit_name = os.environ.get('JUJU_REMOTE_UNIT', '')
if remote_app_name or remote_unit_name:
if not remote_app_name:
if '/' not in remote_unit_name:
raise RuntimeError(f'invalid remote unit name: {remote_unit_name}')
remote_app_name = remote_unit_name.split('/')[0]
args = [relation, model.get_app(remote_app_name)]
if remote_unit_name:
args.append(model.get_unit(remote_unit_name))
return args, {}
elif relation:
return [relation], {}
return [], {}
def main(charm_class):
"""Setup the charm and dispatch the observed event.
The event name is based on the way this executable was called (argv[0]).
"""
charm_dir = _get_charm_dir()
# Process the Juju event relevant to the current hook execution
# JUJU_HOOK_NAME, JUJU_FUNCTION_NAME, and JUJU_ACTION_NAME are not used
# in order to support simulation of events from debugging sessions.
# TODO: For Windows, when symlinks are used, this is not a valid method of getting an event name (see LP: #1854505).
juju_exec_path = Path(sys.argv[0])
juju_event_name = juju_exec_path.name.replace('-', '_')
if juju_exec_path.parent.name == 'actions':
juju_event_name = f'{juju_event_name}_action'
metadata, actions_metadata = _load_metadata(charm_dir)
meta = ops.charm.CharmMeta(metadata, actions_metadata)
unit_name = os.environ['JUJU_UNIT_NAME']
model = ops.model.Model(unit_name, meta, ops.model.ModelBackend())
# TODO: If Juju unit agent crashes after exit(0) from the charm code
# the framework will commit the snapshot but Juju will not commit its
# operation.
charm_state_path = charm_dir / CHARM_STATE_FILE
framework = ops.framework.Framework(charm_state_path, charm_dir, meta, model)
try:
charm = charm_class(framework, None)
# When a charm is force-upgraded and a unit is in an error state Juju does not run upgrade-charm and
# instead runs the failed hook followed by config-changed. Given the nature of force-upgrading
# the hook setup code is not triggered on config-changed.
# 'start' event is included as Juju does not fire the install event for K8s charms (see LP: #1854635).
if juju_event_name in ('install', 'start', 'upgrade_charm') or juju_event_name.endswith('_storage_attached'):
_setup_event_links(charm_dir, charm)
framework.reemit()
_emit_charm_event(charm, juju_event_name)
framework.commit()
finally:
framework.close()
name: simple-k8s
summary: A simple example Kubernetes charm
description: |
Simple is an example charm used in OSM Hackfests
series:
- kubernetes
deployment:
mode: operator
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.
# charms.osm
A Python library to aid the development of charms for Open Source Mano (OSM)
## SSHProxy
Example:
```python
from charms.osm.sshproxy import SSHProxy
# Check if SSH Proxy has key
if not SSHProxy.has_ssh_key():
# Generate SSH Key
SSHProxy.generate_ssh_key()
# Get generated public and private keys
SSHProxy.get_ssh_public_key()
SSHProxy.get_ssh_private_key()
# Get Proxy
proxy = SSHProxy(
hostname=config["ssh-hostname"],
username=config["ssh-username"],
password=config["ssh-password"],
)
# Verify credentials
verified = proxy.verify_credentials()
if verified:
# Run commands in remote machine
proxy.run("touch /home/ubuntu/touch")
```
## Libansible
```python
from charms.osm import libansible
# Install ansible packages in the charm
libansible.install_ansible_support()
result = libansible.execute_playbook(
"configure-remote.yaml", # Name of the playbook <-- Put the playbook in playbooks/ folder
config["ssh-hostname"],
config["ssh-username"],
config["ssh-password"],
dict_vars, # Dictionary with variables to populate in the playbook
)
```
## Usage
Import submodules:
```bash
git submodule add https://github.com/charmed-osm/charms.osm mod/charms.osm
git submodule add https://github.com/juju/charm-helpers.git mod/charm-helpers # Only for libansible
```
Add symlinks:
```bash
mkdir -p lib/charms
ln -s ../mod/charms.osm/charms/osm lib/charms/osm
ln -s ../mod/charm-helpers/charmhelpers lib/charmhelpers # Only for libansible
```
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment