<repo_name>gatici/mano_monitoring<file_sep>/testSnmp/scale.sh
osm vnf-scale  nss1  5  --scaling-group  udr-vdu-manualscale  --scale-out
<file_sep>/testSnmp/upload.sh
#for  i  in  amf smf upf  udm udr  pcf ausf nrf 
#do
	#osm vnfd-create  mslice1_$i'_vnfd.tar.gz'  
#done
osm vnfd-create snmp_ee_vnf.tar.gz
osm  nsd-create  snmp_ee_ns.tar.gz  
#osm nst-create mslice1_nst3.yaml

<file_sep>/jujumetric_sol06/charm_clean.sh
pushd simple
        rm -rf  manifest.yaml hooks src/ops venv  *.charm
popd

<file_sep>/testSnmp/snmp_ee_vnf/helm-charts/eechart/source/install.sh
#!/bin/bash
##
# 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.
##

echo "installing libraries for snmp generator"

#apt-get install -y ...
apt-get update

apt-get install -y python3-pip unzip build-essential libsnmp-dev wget curl
curl -s https://storage.googleapis.com/golang/go1.11.8.linux-amd64.tar.gz | tar -v -C /usr/local -xz
export PATH=$PATH:/usr/local/go/bin
export GOPATH=/go

go get github.com/go-logfmt/logfmt && go get github.com/go-kit/kit/log

wget -q https://github.com/prometheus/snmp_exporter/archive/v0.17.0.tar.gz -P /tmp/ \
&& tar -C /tmp -xf /tmp/v0.17.0.tar.gz \
&& (cd /tmp/snmp_exporter-0.17.0/generator && go build) \
&& cp /tmp/snmp_exporter-0.17.0/generator/generator /usr/local/bin/snmp_generator

<file_sep>/jujumetric_sol06/replace.sh
osm nsd-delete native_charm-ns
osm vnfd-delete native_charm-vnf
osm vnfd-create native_charm_vnf.tar.gz
osm nsd-create native_charm_ns.tar.gz
<file_sep>/testSnmp/tar.sh
#for  i  in  amf smf upf  udm udr  pcf ausf nrf 
#do
#	tar -czvf  mslice1_$i'_vnfd.tar.gz'  mslice1_$i'_vnfd'
#done
tar  -czvf snmp_ee_ns.tar.gz  snmp_ee_ns
tar  -czvf snmp_ee_vnf.tar.gz  snmp_ee_vnf

<file_sep>/simplehelm/create_ns.sh
osm ns-create --ns_name  helmtest  --nsd_name  simple_ee-ns    --vim_account  osm_com115
<file_sep>/jujumetric_sol06/create_ns.sh
osm ns-create --ns_name  jujumetrics1  --nsd_name  native_charm-ns    --vim_account  osm_com115_v3
<file_sep>/simplehelm/simple_ee_vnf/helm-charts/eechart/source/vnf_ee.py
##
# Copyright 2019 Telefonica Investigacion y Desarrollo, S.A.U.
# This file is part of OSM
# 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.
#
# For those usages not covered by the Apache License, Version 2.0 please
# contact with: <EMAIL>
##

import asyncio
import logging
import asyncssh


from osm_ee.exceptions import VnfException


class VnfEE:

    def __init__(self, config_params):
        self.logger = logging.getLogger('osm_ee.vnf')
        self.config_params = config_params

    async def config(self, id, params):
        self.logger.debug("Execute action config params: {}".format(params))
        # Config action is special, params are merged with previous config calls
        self.config_params.update(params)
        required_params = ["ssh-hostname"]
        self._check_required_params(self.config_params, required_params)
        yield "OK", "Configured"

    async def touch(self, id, params):
        self.logger.debug("Execute action touch params: '{}', type: {}".format(params, type(params)))

        try:
            self._check_required_params(params, ["file-path"])

            # Check if filename is a single file or a list
            file_list = params["file-path"] if isinstance(params["file-path"], list) else [params["file-path"]]
            file_list_length = len(file_list)

            async with asyncssh.connect(self.config_params["ssh-hostname"],
                                        password=self.config_params.get("ssh-password"),
                                        username=self.config_params.get("ssh-username"),
                                        known_hosts=None) as conn:
                for index, file_name in enumerate(file_list):
                    command = "touch {}".format(file_name)
                    self.logger.debug("Execute remote  command: '{}'".format(command))
                    result = await conn.run(command)
                    self.logger.debug("Create command result: {}".format(result))

                    if result.exit_status != 0:
                        detailed_status = result.stderr
                        # TODO - ok but with some errors
                    else:
                        detailed_status = "Created file {}".format(file_name)

                    if index + 1 != file_list_length:
                        yield "PROCESSING", detailed_status
                    else:
                        yield "OK", detailed_status
        except Exception as e:
            self.logger.error("Error creating remote file: {}".format(repr(e)))
            yield "ERROR", str(e)

    async def sleep(self, id, params):
        self.logger.debug("Execute action sleep, params: {}".format(params))

        for i in range(3):
            await asyncio.sleep(5)
            self.logger.debug("Temporal result return, params: {}".format(params))
            yield "PROCESSING", f"Processing {i} action id {id}"
        yield "OK", f"Processed action id {id}"

    @staticmethod
    def _check_required_params(params, required_params):
        for required_param in required_params:
            if required_param not in params:
                raise VnfException("Missing required param: {}".format(required_param))
<file_sep>/testSnmp/snmp_ee_vnf/helm-charts/eechart/source/vnf_ee.py
##
# 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 asyncio
import logging
import os


from osm_ee.exceptions import VnfException

import osm_ee.util.util_ee as util_ee


class VnfEE:

    def __init__(self, config_params):
        self.logger = logging.getLogger('osm_ee.vnf')
        self.config_params = config_params

    async def config(self, id, params):
        self.logger.debug("Execute action config params: {}".format(params))
        # Config action is special, params are merged with previous config calls
        self.config_params.update(params)
        required_params = ["ssh-hostname"]
        self._check_required_params(self.config_params, required_params)
        yield "OK", "Configured"

    async def sleep(self, id, params):
        self.logger.debug("Execute action sleep, params: {}".format(params))

        for i in range(3):
            await asyncio.sleep(5)
            self.logger.debug("Temporal result return, params: {}".format(params))
            yield "PROCESSING", f"Processing {i} action id {id}"
        yield "OK", f"Processed action id {id}"

    async def generate_snmp(self, id, params):
        self.logger.debug("Executing SNMP exporter configuration generation\nWith params: {}".format(params))

        commands =  ("cp /app/vnf/generator/generator.yml ./",
                     "snmp_generator generate --output-path=/etc/snmp_exporter/snmp.yml",
                     "touch /etc/snmp_exporter/generator.yml")
        for command in commands:
            return_code, stdout, stderr = await util_ee.local_async_exec(command)
            if return_code != 0:
                yield "ERROR", "return code {}: {}".format(return_code, stderr.decode())
                break
        else:
            yield "OK", stdout.decode()

    @staticmethod
    def _check_required_params(params, required_params):
        for required_param in required_params:
            if required_param not in params:
                raise VnfException("Missing required param: {}".format(required_param))
<file_sep>/simplehelm/upload.sh
#for  i  in  amf smf upf  udm udr  pcf ausf nrf 
#do
	#osm vnfd-create  mslice1_$i'_vnfd.tar.gz'  
#done
osm vnfd-create simple_ee_vnf.tar.gz
osm  nsd-create  simple_ee_ns.tar.gz  
#osm nst-create mslice1_nst3.yaml

<file_sep>/jujumetric_sol06/native_charm_vnf/charms/simple/build/stage/src/charm.py
#!/usr/bin/env python3
##
# Copyright 2020 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
import subprocess

sys.path.append("lib")
import logging

from ops.charm import CharmBase
from ops.main import main
from ops.model import ActiveStatus

logger = logging.getLogger(__name__)

def get_metric(cmd):
    out = subprocess.check_output(cmd, shell=True)
    out = out.decode("utf-8").strip()
    return float(out)

class MyNativeCharm(CharmBase):

    def __init__(self, *args):
        super().__init__(*args)

        # Listen to charm events

        self.framework.observe(self.on.install, self._on_install)
        self.framework.observe(self.on.start, self._on_start)
        self.framework.observe(self.on.config_changed, self._on_config_changed)
        self.framework.observe(self.on.update_status, self._on_update_status)
        self.framework.observe(self.on.collect_metrics, self.on_collect_metrics)


        # Listen to the touch action event
        self.framework.observe(self.on.touch_action, self.on_touch_action)


    
    def _on_config_changed(self, _):
        self.unit.status = ActiveStatus()

    def _on_update_status(self, _):
        self.unit.status = ActiveStatus()

    def _on_install(self, event):
        """Called when the charm is being installed"""
        self.model.unit.status = ActiveStatus()

    def _on_start(self, event):
        """Called when the charm is being started"""
        self.model.unit.status = ActiveStatus()

    def on_touch_action(self, event):
        """Touch a file."""

        filename = event.params["filename"]
        try:
            subprocess.run(["touch", filename], check=True)
            event.set_results({"created": True, "filename": filename})
        except subprocess.CalledProcessError as e:
            event.fail("Action failed: {}".format(e))
        self.model.unit.status = ActiveStatus()

    def on_collect_metrics(self, event):
        mem_free = get_metric("free | grep Mem | awk '{print 100*$3/$2}'")
        cpu_util = get_metric("top -b -n2 | grep \"Cpu(s)\"|tail -n 1 | awk '{print $2 + $4}'")

        logger.debug(f"Free memory: {mem_free}")
        logger.debug(f"Cpu utilization: {cpu_util}")

        event.add_metrics({"mem_free": int(mem_free), "cpu_util": int(cpu_util)})




if __name__ == "__main__":
    main(MyNativeCharm)

<file_sep>/simplehelm/tar.sh
#for  i  in  amf smf upf  udm udr  pcf ausf nrf 
#do
	tar -czvf  mslice1_$i'_vnfd.tar.gz'  mslice1_$i'_vnfd'
#done
tar  -czvf simple_ee_ns.tar.gz  simple_ee_ns
tar  -czvf simple_ee_vnf.tar.gz  simple_ee_vnf

<file_sep>/simplehelm/remove.sh
#osm nst-delete  mslice1_nst
osm  nsd-delete  simple_ee-ns
#for  i  in  amf smf upf  udm udr  pcf ausf nrf 
#do
	#osm vnfd-delete  mslice1_$i'_vnfd'  
#done
osm vnfd-delete simple_ee-vnf
<file_sep>/jujumetric_sol06/charm_build.sh
pushd simple
        charmcraft  build
        cp -r  build/prime/*  .
        cp -r  venv/ops  src/
popd

<file_sep>/jujumetric_sol06/simple/venv/ops-1.2.0.dist-info/DESCRIPTION.rst
# The Charmed Operator Framework

This Charmed Operator Framework simplifies [Kubernetes
operator](https://charmhub.io/about) development for 
[model-driven application
management](https://juju.is/model-driven-operations).

A Kubernetes operator is a container that drives lifecycle management,
configuration, integration and daily actions for an application.
Operators simplify software management and operations. They capture
reusable app domain knowledge from experts in a software component that
can be shared.

This project extends the operator pattern to enable 
[charmed operators](https://juju.is/universal-operators), not just
for Kubernetes but also operators for traditional Linux or Windows
application management.

Operators use a [Charmed Operator Lifecycle Manager
(Charmed OLM)](https://juju.is/operator-lifecycle-manager) to coordinate their
work in a cluster. The system uses Golang for concurrent event
processing under the hood, but enables the operators to be written in
Python.

## Simple, composable operators

Operators should 'do one thing and do it well'. Each operator drives a
single microservice and can be [composed with other 
operators](https://juju.is/integration) to deliver a complex application.

It is better to have small, reusable operators that each drive a single
microservice very well. The operator handles instantiation, scaling,
configuration, optimisation, networking, service mesh, observability,
and day-2 operations specific to that microservice.

Operator composition takes place through declarative integration in
the OLM. Operators declare integration endpoints, and discover lines of
integration between those endpoints dynamically at runtime.

## Pure Python operators

The framework provides a standard Python library and object model that
represents the application graph, and an event distribution mechanism for
distributed system coordination and communication.

The OLM is written in Golang for efficient concurrency in event handling
and distribution. Operators can be written in any language. We recommend
this Python framework for ease of design, development and collaboration.

## Better collaboration

Operator developers publish Python libraries that make it easy to integrate
your operator with their operator. The framework includes standard tools
to distribute these integration libraries and keep them up to date.

Development collaboration happens at [Charmhub.io](https://charmhub.io/) where
operators are published along with integration libraries. Design and
code review discussions are hosted in the
[Charmhub forum](https://discourse.charmhub.io/). We recommend the
[Open Operator Manifesto](https://charmhub.io/manifesto) as a guideline for
high quality operator engineering.

## Event serialization and operator services

Distributed systems can be hard! So this framework exists to make it much
simpler to reason about operator behaviour, especially in complex deployments.
The Charmed OLM provides [operator services](https://juju.is/operator-services) such
as provisioning, event delivery, leader election and model management.

Coordination between operators is provided by a cluster-wide event
distribution system. Events are serialized to avoid race conditions in any
given container or machine. This greatly simplifies the development of
operators for high availability, scale-out and integrated applications.

## Model-driven Operator Lifecycle Manager

A key goal of the project is to improve the user experience for admins
working with multiple different operators.

We embrace [model-driven operations](https://juju.is/model-driven-operations)
in the Charmed Operator Lifecycle Manager. The model encompasses capacity,
storage, networking, the application graph and administrative access.

Admins describe the application graph of integrated microservices, and
the OLM then drives instantiation. A change in the model is propagated
to all affected operators, reducing the duplication of effort and
repetition normally found in operating a complex topology of services.

Administrative actions, updates, configuration and integration are all
driven through the OLM.

# Getting started

A package of operator code is called a charmed operator or “charm. You will use `charmcraft`
to register your operator name, and publish it when you are ready.

```
$ sudo snap install charmcraft --beta
charmcraft (beta) 0.6.0 from <NAME> (chipaca) installed
```

Charmed operators written using the Charmed Operator Framework are just Python code. The goal
is to feel natural for somebody used to coding in Python, and reasonably
easy to learn for somebody who is not a pythonista.

The dependencies of the operator framework are kept as minimal as possible;
currently that's Python 3.5 or greater, and `PyYAML` (both are included by
default in Ubuntu's cloud images from 16.04 on).

# A quick introduction

Make an empty directory `my-charm` and cd into it. Then start a new charmed operator
with:

```
$ charmcraft init
All done.
There are some notes about things we think you should do.
These are marked with ‘TODO:’, as is customary. Namely:
      README.md: fill out the description
      README.md: explain how to use the charm
  metadata.yaml: fill out the charm's description
  metadata.yaml: fill out the charm's summary
```

Charmed operators are just Python code. The entry point to your charmed operator can
be any filename, by default this is `src/charm.py` which must be executable
(and probably have `#!/usr/bin/env python3` on the first line).

You need a `metadata.yaml` to describe your charmed operator, and if you will support
configuration of your charmed operator then `config.yaml` files is required too. The
`requirements.txt` specifies any Python dependencies.

```
$ tree my-charm/
my-charm/
├── actions.yaml
├── config.yaml
├── LICENSE
├── metadata.yaml
├── README.md
├── requirements-dev.txt
├── requirements.txt
├── run_tests
├── src
│   └── charm.py
├── tests
│   ├── __init__.py
│   └── my_charm.py
```

`src/charm.py` here is the entry point to your charm code. At a minimum, it
needs to define a subclass of `CharmBase` and pass that into the framework
`main` function:

```python
from ops.charm import CharmBase
from ops.main import main

class MyCharm(CharmBase):
    def __init__(self, *args):
        super().__init__(*args)
        self.framework.observe(self.on.start, self.on_start)

    def on_start(self, event):
        # Handle the start event here.

if __name__ == "__main__":
    main(MyCharm)
```

That should be enough for you to be able to run

```
$ charmcraft build
Done, charm left in 'my-charm.charm'
$ juju deploy ./my-charm.charm
```

> 🛈 More information on [`charmcraft`](https://pypi.org/project/charmcraft/) can
> also be found on its [github page](https://github.com/canonical/charmcraft).

Happy charming!

# Testing your charmed operators

The operator framework provides a testing harness, so you can check your
charmed operator does the right thing in different scenarios, without having to create
a full deployment. `pydoc3 ops.testing` has the details, including this
example:

```python
harness = Harness(MyCharm)
# Do initial setup here
relation_id = harness.add_relation('db', 'postgresql')
# Now instantiate the charm to see events as the model changes
harness.begin()
harness.add_relation_unit(relation_id, 'postgresql/0')
harness.update_relation_data(relation_id, 'postgresql/0', {'key': 'val'})
# Check that charm has properly handled the relation_joined event for postgresql/0
self.assertEqual(harness.charm. ...)
```

## Talk to us

If you need help, have ideas, or would just like to chat with us, reach out on
IRC: we're in [#smooth-operator] on freenode (or try the [webchat]).

We also pay attention to [Charmhub discourse](https://discourse.charmhub.io/)

You can also deep dive into the [API docs] if that's your thing.

[webchat]: https://webchat.freenode.net/#smooth-operator
[#smooth-operator]: irc://chat.freenode.net/%23smooth-operator
[discourse]: https://discourse.juju.is/c/charming
[API docs]: https://ops.rtfd.io/

## Operator Framework development

To work in the framework itself you will need Python >= 3.5 and the
dependencies in `requirements-dev.txt` installed in your system, or a
virtualenv:

    virtualenv --python=python3 env
    source env/bin/activate
    pip install -r requirements-dev.txt

Then you can try `./run_tests`, it should all go green.

For improved performance on the tests, ensure that you have PyYAML
installed with the correct extensions:

    apt-get install libyaml-dev
    pip install --force-reinstall --no-cache-dir pyyaml

If you want to build the documentation you'll need the requirements from
`docs/requirements.txt`, or in your virtualenv

    pip install -r docs/requirements.txt

and then you can run `./build_docs`.


