Custom Search
Showing posts with label OpenStack. Show all posts
Showing posts with label OpenStack. Show all posts

Friday, December 6, 2019

How to Decode or Decrypt OpenStack Keystone Token

sudo python

import keystone

from keystone.token import token_formatters

formatter = token_formatters.TokenFormatter()

t = "gAAAAABd6Wl0RnnFOcy-q6aFWlr__bDcxk-GFFrLZsDh3z38Abg0iH5yFOJP7QyOVZ1SUhlIqxgID89hsZnubsM5hsbQSsYLujhU1_Zz9hlowb0chks9mogf4Pp9f1JFkr3FVQaCv2MN-ykpARLSpoV9c3m-7EFASaUNwMgysXC734598mKmWbI"

from keystone import server
server.configure()

validated_dict = formatter.validate_token(t)

validated_dict

>>> validated_dict
('a647d82c28aa4267bcf2ea99c328cd48', ['password'], [u'd6yYRIWASaKrjKTRwoGyNA'], None, None, '66cbc35f0b99430987357c2526945f8b', None, None, None, None, None, None, '2019-12-05T21:38:53.000000Z', '2019-12-05T22:38:53.000000Z')
>>> 

Monday, July 24, 2017

Openstack How to do doc8 scan

1)
Got your project folder (cloned from github)

2)
$ tox -v -epep8

3)
$ source .tox/pep8/bin/activate

4)
$ doc8 -e .rst doc/source/

* .rst means scan only *.rst files


OpenStack Creating release notes with Reno

https://docs.openstack.org/reno/latest/user/usage.html

1)
https://docs.openstack.org/reno/latest/install/index.html
$ pip install reno

2)
The reno command line tool is used to create a new release note file in the correct format and with a unique name.

$ tox reno new my-new-release1

By default, the new note is created under ./releasenotes/notes.

OR

$ tox -e venv -- reno new my-new-release1
$ source .tox/venv/bin/activate

3)

Friday, March 10, 2017

How to git github rename local and remote branch

$git clone your_project
$git checkout old_branch_name
$git branch -m new_branch_name
$git push origin : old_branch_name new_branch_name


Sunday, March 5, 2017

How to clear OpenStack Nova instance table

delete from instance_faults;
delete from instance_extra;
delete from instance_info_caches;
delete from instance_system_metadata;
delete from block_device_mapping;
delete from instances;

apparmor="DENIED" operation="exec" profile="/usr/sbin/libvirtd" name="/usr/local/bin/qemu-system-alpha" pid=2392 comm="libvirtd" requested_mask="x" denied_mask="x" fsuid=0 ouid=0

Fix:
$service apparmor teardown <=============works

https://bugs.launchpad.net/ubuntu/+source/libvirt/+bug/632696

==========Error=========

/var/log/syslog

Mar  3 20:10:39 localhost kernel: [4260864.783747] audit_printk_skb: 294 callbacks suppressed
Mar  3 20:10:39 localhost kernel: [4260864.783752] type=1400 audit(1488571839.231:3944): apparmor="DENIED" operation="exec" profile="/usr/sbin/libvirtd" name="/usr/local/bin/qemu-system-alpha" pid=2392 comm="libvirtd" requested_mask="x" denied_mask="x" fsuid=0 ouid=0
Mar  3 20:10:39 localhost kernel: [4260864.789692] type=1400 audit(1488571839.235:3945): apparmor="DENIED" operation="exec" profile="/usr/sbin/libvirtd" name="/usr/local/bin/qemu-system-alpha" pid=2393 comm="libvirtd" requested_mask="x" denied_mask="x" fsuid=0 ouid=0
Mar  3 20:10:39 localhost kernel: [4260864.797468] type=1400 audit(1488571839.243:3946): apparmor="DENIED" operation="exec" profile="/usr/sbin/libvirtd" name="/usr/local/bin/qemu-system-arm" pid=2394 comm="libvirtd" requested_mask="x" denied_mask="x" fsuid=0 ouid=0
Mar  3 20:10:39 localhost kernel: [4260864.800058] type=1400 audit(1488571839.243:3947): apparmor="DENIED" operation="exec" profile="/usr/sbin/libvirtd" name="/usr/local/bin/qemu-system-arm" pid=2395 comm="libvirtd" requested_mask="x" denied_mask="x" fsuid=0 ouid=0
Mar  3 20:10:39 localhost kernel: [4260864.800058] type=1400 audit(1488571839.243:3948): apparmor="DENIED" operation="exec" profile="/usr/sbin/libvirtd" name="/usr/local/bin/qemu-system-aarch64" pid=2396 comm="libvirtd" requested_mask="x" denied_mask="x" fsuid=0 ouid=0
Mar  3 20:10:39 localhost kernel: [4260864.800058] type=1400 audit(1488571839.243:3949): apparmor="DENIED" operation="exec" profile="/usr/sbin/libvirtd" name="/usr/local/bin/qemu-system-aarch64" pid=2397 comm="libvirtd" requested_mask="x" denied_mask="x" fsuid=0 ouid=0
Mar  3 20:10:39 localhost kernel: [4260864.800058] type=1400 audit(1488571839.243:3950): apparmor="DENIED" operation="exec" profile="/usr/sbin/libvirtd" name="/usr/local/bin/qemu-system-cris" pid=2398 comm="libvirtd" requested_mask="x" denied_mask="x" fsuid=0 ouid=0
Mar  3 20:10:39 localhost kernel: [4260864.800058] type=1400 audit(1488571839.243:3951): apparmor="DENIED" operation="exec" profile="/usr/sbin/libvirtd" name="/usr/local/bin/qemu-system-cris" pid=2399 comm="libvirtd" requested_mask="x" denied_mask="x" fsuid=0 ouid=0
Mar  3 20:10:39 localhost kernel: [4260864.800058] type=1400 audit(1488571839.243:3952): apparmor="DENIED" operation="exec" profile="/usr/sbin/libvirtd" name="/usr/local/bin/qemu-system-i386" pid=2400 comm="libvirtd" requested_mask="x" denied_mask="x" fsuid=0 ouid=0
Mar  3 20:10:39 localhost kernel: [4260864.800058] type=1400 audit(1488571839.243:3953): apparmor="DENIED" operation="exec" profile="/usr/sbin/libvirtd" name="/usr/local/bin/qemu-system-i386" pid=2401 comm="libvirtd" requested_mask="x" denied_mask="x" fsuid=0 ouid=0

How to fix libvirtError: internal error: Cannot find suitable emulator for x86_64

Fix:
$service apparmor teardown <=============works

https://bugs.launchpad.net/ubuntu/+source/libvirt/+bug/632696

==========Error==========
2017-03-03 19:58:56.513 ERROR oslo_service.service [-] Error starting thread.
2017-03-03 19:58:56.513 TRACE oslo_service.service Traceback (most recent call last):
2017-03-03 19:58:56.513 TRACE oslo_service.service   File "/usr/local/lib/python2.7/dist-packages/oslo_service/service.py", line 722, in run_service
2017-03-03 19:58:56.513 TRACE oslo_service.service     service.start()
2017-03-03 19:58:56.513 TRACE oslo_service.service   File "/opt/stack/nova/nova/service.py", line 144, in start
2017-03-03 19:58:56.513 TRACE oslo_service.service     self.manager.init_host()
2017-03-03 19:58:56.513 TRACE oslo_service.service   File "/opt/stack/nova/nova/compute/manager.py", line 1138, in init_host
2017-03-03 19:58:56.513 TRACE oslo_service.service     self.driver.init_host(host=self.host)
2017-03-03 19:58:56.513 TRACE oslo_service.service   File "/opt/stack/nova/nova/virt/libvirt/driver.py", line 471, in init_host
2017-03-03 19:58:56.513 TRACE oslo_service.service     self._parse_migration_flags()
2017-03-03 19:58:56.513 TRACE oslo_service.service   File "/opt/stack/nova/nova/virt/libvirt/driver.py", line 629, in _parse_migration_flags
2017-03-03 19:58:56.513 TRACE oslo_service.service     live_migration_flags)
2017-03-03 19:58:56.513 TRACE oslo_service.service   File "/opt/stack/nova/nova/virt/libvirt/driver.py", line 605, in _handle_live_migration_auto_converge
2017-03-03 19:58:56.513 TRACE oslo_service.service     if (self._is_post_copy_available() and
2017-03-03 19:58:56.513 TRACE oslo_service.service   File "/opt/stack/nova/nova/virt/libvirt/driver.py", line 587, in _is_post_copy_available
2017-03-03 19:58:56.513 TRACE oslo_service.service     hv_ver=MIN_QEMU_POSTCOPY_VERSION):
2017-03-03 19:58:56.513 TRACE oslo_service.service   File "/opt/stack/nova/nova/virt/libvirt/host.py", line 522, in has_min_version
2017-03-03 19:58:56.513 TRACE oslo_service.service     lv_ver=lv_ver, hv_ver=hv_ver, hv_type=hv_type, op=operator.lt)
2017-03-03 19:58:56.513 TRACE oslo_service.service   File "/opt/stack/nova/nova/virt/libvirt/host.py", line 495, in _version_check
2017-03-03 19:58:56.513 TRACE oslo_service.service     conn = self.get_connection()
2017-03-03 19:58:56.513 TRACE oslo_service.service libvirtError: internal error: Cannot find suitable emulator for x86_64
2017-03-03 19:58:56.513 TRACE oslo_service.service

How to fix libvirtError: authentication failed: no agent is available to authenticate

Fix:

$ sudo vim  /etc/libvirt/libvirtd.conf

# If the unix_sock_rw_perms are changed you may wish to enable
# an authentication mechanism here
auth_unix_rw = "none"

==========Error==========

2017-03-03 15:54:38.088 DEBUG nova.virt.libvirt.host [-] Connecting to libvirt: qemu:///system from (pid=6113) _get_new_connection /opt/stack/nova/no
va/virt/libvirt/host.py:368
2017-03-03 15:54:38.114 ERROR nova.virt.libvirt.host [-] Connection to libvirt failed: authentication failed: no agent is available to authenticate
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host Traceback (most recent call last):
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host   File "/opt/stack/nova/nova/virt/libvirt/host.py", line 454, in get_connection
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host     conn = self._get_connection()
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host   File "/opt/stack/nova/nova/virt/libvirt/host.py", line 437, in _get_connection
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host     {'msg': ex})
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host   File "/usr/local/lib/python2.7/dist-packages/oslo_utils/excutils.py", line 220, in __exit__
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host     self.force_reraise()
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host   File "/usr/local/lib/python2.7/dist-packages/oslo_utils/excutils.py", line 196, in force_reraise
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host     six.reraise(self.type_, self.value, self.tb)
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host   File "/opt/stack/nova/nova/virt/libvirt/host.py", line 426, in _get_connection
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host     self._wrapped_conn = self._get_new_connection()
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host   File "/opt/stack/nova/nova/virt/libvirt/host.py", line 371, in _get_new_connection
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host     wrapped_conn = self._connect(self._uri, self._read_only)
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host   File "/opt/stack/nova/nova/virt/libvirt/host.py", line 227, in _connect
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host     libvirt.openAuth, uri, auth, flags)
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host   File "/usr/local/lib/python2.7/dist-packages/eventlet/tpool.py", line 144, in proxy_call
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host     rv = execute(f, *args, **kwargs)
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host   File "/usr/local/lib/python2.7/dist-packages/eventlet/tpool.py", line 125, in execute
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host     six.reraise(c, e, tb)
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host   File "/usr/local/lib/python2.7/dist-packages/eventlet/tpool.py", line 83, in tworker
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host     rv = meth(*args, **kwargs)
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host   File "/usr/local/lib/python2.7/dist-packages/libvirt.py", line 105, in openAuth
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host     if ret is None:raise libvirtError('virConnectOpenAuth() failed')
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host libvirtError: authentication failed: no agent is available to authenticate
2017-03-03 15:54:38.114 TRACE nova.virt.libvirt.host
2017-03-03 15:54:38.143 INFO nova.virt.libvirt.driver [-] Connection event '0' reason 'Failed to connect to libvirt: authentication failed: no agent is available to authenticate'
2017-03-03 15:54:38.145 DEBUG oslo_messa

=====================

2017-03-03 15:35:31.040 ERROR oslo_service.service [req-d687bfd4-f9d8-4031-a2bb-b6df6a9abc12 None None] Error starting thread.
2017-03-03 15:35:31.040 TRACE oslo_service.service Traceback (most recent call last):
2017-03-03 15:35:31.040 TRACE oslo_service.service   File "/usr/local/lib/python2.7/dist-packages/oslo_service/service.py", line 722, in run_service
2017-03-03 15:35:31.040 TRACE oslo_service.service     service.start()
2017-03-03 15:35:31.040 TRACE oslo_service.service   File "/opt/stack/nova/nova/service.py", line 144, in start
2017-03-03 15:35:31.040 TRACE oslo_service.service     self.manager.init_host()
2017-03-03 15:35:31.040 TRACE oslo_service.service   File "/opt/stack/nova/nova/compute/manager.py", line 1138, in init_host
2017-03-03 15:35:31.040 TRACE oslo_service.service     self.driver.init_host(host=self.host)
2017-03-03 15:35:31.040 TRACE oslo_service.service   File "/opt/stack/nova/nova/virt/libvirt/driver.py", line 469, in init_host
2017-03-03 15:35:31.040 TRACE oslo_service.service     self._do_quality_warnings()
2017-03-03 15:35:31.040 TRACE oslo_service.service   File "/opt/stack/nova/nova/virt/libvirt/driver.py", line 446, in _do_quality_warnings
2017-03-03 15:35:31.040 TRACE oslo_service.service     caps = self._host.get_capabilities()
2017-03-03 15:35:31.040 TRACE oslo_service.service   File "/opt/stack/nova/nova/virt/libvirt/host.py", line 639, in get_capabilities
2017-03-03 15:35:31.040 TRACE oslo_service.service     xmlstr = self.get_connection().getCapabilities()
2017-03-03 15:35:31.040 TRACE oslo_service.service   File "/opt/stack/nova/nova/virt/libvirt/host.py", line 463, in get_connection
2017-03-03 15:35:31.040 TRACE oslo_service.service     raise exception.HypervisorUnavailable(host=CONF.host)
2017-03-03 15:35:31.040 TRACE oslo_service.service HypervisorUnavailable: Connection to the hypervisor is broken on host: masterneutron
2017-03-03 15:35:31.040 TRACE oslo_service.service
2017-03-03 15:35:31.051 DEBUG oslo_concurrency.lockutils [req-b130d18f-6c7f-4c3c-b4e4-18e057e647b0 None None] Acquired semaphore "singleton_lock" from (pid=5403) lock /usr/local/lib/python2.7/dist-packages/oslo

Saturday, March 4, 2017

Howto VirtualBox VBoxManage increase number of cpus

$ vboxmanage list vms

$ Poweroff the VM

$ VBoxManage modifyvm my-vm-name --cpuhotplug on

$ VBoxManage controlvm my-vm-name plugcpu 0
$ VBoxManage controlvm my-vm-name plugcpu 1
$ VBoxManage controlvm my-vm-name plugcpu 2
$ VBoxManage controlvm my-vm-name plugcpu 3
$ VBoxManage controlvm my-vm-name plugcpu 4
$ VBoxManage controlvm my-vm-name plugcpu 5

$Poweron the VM

$ cat /proc/cpuinfo | grep processor | wc -l
6

Friday, March 3, 2017

How to compile and install QEMU version 2.1.0 or greater

$qemu-system-x86_64 --version

$sudo apt-get install build-essential zlib1g-dev

$sudo apt-get --no-install-recommends -y build-dep qemu

$wget http://wiki.qemu-project.org/download/qemu-2.1.0.tar.bz2

$tar -xvf qemu-2.1.0.tar.bz2

$cd qemu-2.1.0/

$./configure

$make

$sudo make install


InternalError: Nova requires libvirt version 1.2.9 or greater.

$wget https://libvirt.org/sources/libvirt-1.2.9.tar.gz

$sudo apt-get build-dep libvirt

$sudo tar xvzf libvirt-1.2.9.tar.gz -C /usr/src

$cd /usr/src/libvirt-1.2.9




$sudo ./configure --prefix=/usr/

$sudo make

$sudo make install


Sunday, July 26, 2015

OpenStack zeromq send_multipart code trace from oslo.messaging._drivers.impl_zmq to eventlet.green.zmq to pyzmq

OpenStack zeromq send_multipart code trace from oslo.messaging._drivers.impl_zmq to eventlet.green.zmq to pyzmq

1)

https://github.com/JioCloud/oslo.messaging/blob/stable/icehouse/oslo/messaging/_drivers/impl_zmq.py#L216

zmq = importutils.try_import('eventlet.green.zmq') <=====1

class ZmqSocket(object):

    """A tiny wrapper around ZeroMQ.

    Simplifies the send/recv protocol and connection management.
    Can be used as a Context (supports the 'with' statement).
    """
    def __init__(self, addr, zmq_type, bind=True, subscribe=None):
        self.sock = _get_ctxt().socket(zmq_type) <=====4

    def send(self, data, **kwargs):
        if not self.can_send:
            raise RPCException(_("You cannot send on this socket."))
        self.sock.send_multipart(data, **kwargs) <====8

def _get_ctxt():

    if not zmq:
        raise ImportError("Failed to import eventlet.green.zmq")
    global ZMQ_CTX
    if not ZMQ_CTX:
        ZMQ_CTX = zmq.Context(CONF.rpc_zmq_contexts) <=====2
    return ZMQ_CTX

2)
https://github.com/eventlet/eventlet/blob/master/eventlet/green/zmq.py#L302

__zmq__ = __import__('zmq')
_Socket = __zmq__.Socket
_Socket_send_multipart = _Socket.send_multipart<=====10

class Context(__zmq__.Context): <=====3
    """Subclass of :class:`zmq.core.context.Context`
    """
    def socket(self, socket_type): <=====5
        """Overridden method to ensure that the green version of socket is used

        Behaves the same as :meth:`zmq.core.context.Context.socket`, but ensures
        that a :class:`Socket` with all of its send and recv methods set to be
        non-blocking is returned
        """
        if self.closed:
            raise ZMQError(ENOTSUP)
        return Socket(self, socket_type) <=====6

class Socket(_Socket): <=====7
    @_wraps(_Socket.send_multipart)<=====9
    def send_multipart(self, msg_parts, flags=0, copy=True, track=False): <=====12
        """A send_multipart method that's safe to use when multiple
        greenthreads are calling send, send_multipart, recv and
        recv_multipart on the same socket.
        """
        if flags & NOBLOCK:
            return _Socket_send_multipart(self, msg_parts, flags, copy, track) <=====13/or

        # acquire lock here so the subsequent calls to send for the
        # message parts after the first don't block
        with self._eventlet_send_lock:
            return _Socket_send_multipart(self, msg_parts, flags, copy, track) <=====13/or

def _wraps(source_fn): <=====11
    """A decorator that copies the __name__ and __doc__ from the given
    function
    """
    def wrapper(dest_fn):
        dest_fn.__name__ = source_fn.__name__
        dest_fn.__doc__ = source_fn.__doc__
        return dest_fn
    return wrapper

3)
https://github.com/zeromq/pyzmq/blob/4b8c8a680bb86fc6e0a82447abd7821f046a026a/zmq/sugar/socket.py#L47

import zmq
from zmq.backend import Socket as SocketBase <======17

class Socket(SocketBase, AttributeSetter):
    def send_multipart(self, msg_parts, flags=0, copy=True, track=False): <=====14
        for i,msg in enumerate(msg_parts):
            if isinstance(msg, (zmq.Frame, bytes, _buffer_type)):
                continue
            try:
                _buffer_type(msg)
            except Exception as e:
                rmsg = repr(msg)
                if len(rmsg) > 32:
                    rmsg = rmsg[:32] + '...'
                raise TypeError(
                    "Frame %i (%s) does not support the buffer interface." % (
                    i, rmsg,
                ))
        for msg in msg_parts[:-1]: <======15
            self.send(msg, SNDMORE|flags, copy=copy, track=track) <======16
        # Send the last part without the extra SNDMORE flag.
        return self.send(msg_parts[-1], flags, copy=copy, track=track)   

__all__ = ['Socket'] <=====

4)
https://github.com/zeromq/pyzmq/blob/master/zmq/backend/__init__.py

from .select import public_api, select_backend

backend = os.environ['PYZMQ_BACKEND'] <====a (Find Backend 'cython' or 'cffi')
if backend in ('cython', 'cffi'):
    backend = 'zmq.backend.%s' % backend

_ns = select_backend(backend) <====b (Load backend api modules)
globals().update(_ns)

__all__ = public_api

5)
https://github.com/zeromq/pyzmq/blob/master/zmq/backend/select.py

public_api = [  <====c (Backend api modules list)
    'Context',
    'Socket',
    ... ...
    ]
   
def select_backend(name):
    mod = __import__(name, fromlist=public_api) <====d (Load backend api modules)

6)

Here, selected backend is "cython"
https://github.com/zeromq/pyzmq/tree/master/zmq/backend/cython

7)
https://github.com/zeromq/pyzmq/blob/master/zmq/backend/cython/socket.pyx#L619

cdef class Socket: <======18
    cpdef object send(self, object data, int flags=0, copy=True, track=False): <======19
        _check_closed(self)
       
        if isinstance(data, unicode):
            raise TypeError("unicode not allowed, use send_string")
       
        if copy:
            # msg.bytes never returns the input data object
            # it is always a copy, but always the same copy
            if isinstance(data, Frame):
                data = data.buffer
            return _send_copy(self.handle, data, flags) <======20
        else:
            if isinstance(data, Frame):
                if track and not data.tracker:
                    raise ValueError('Not a tracked message')
                msg = data
            else:
                msg = Frame(data, track=track)
            return _send_frame(self.handle, msg, flags)
           
cdef inline object _send_copy(void *handle, object msg, int flags=0): <======21
    rc = zmq_msg_init_size(&data, msg_c_len)
    _check_rc(rc)
   
    while True:
        with nogil:
            memcpy(zmq_msg_data(&data), msg_c, zmq_msg_size(&data))
            rc = zmq_msg_send(&data, handle, flags) <======22
            if not rc < 0:
                rc2 = zmq_msg_close(&data)
        try:
            _check_rc(rc)
        except InterruptedSystemCall:
            continue
        else:
            break
    _check_rc(rc2)

Friday, May 15, 2015

OpenStack Create a VM in a selected subnet


Create a VM in selected subnet using IP in that subnet
#nova boot --flavor 1 --image e489afe7-add9-414e-9349-bfa737f02b73 --security-groups 989a351c-9448-4b52-a14f-3eb49ccb33ed --nic net-id=aeaf3661-cded-408f-9210-6917a6a60b87,v4-fixed-ip=10.2.2.10 sa-vm1

* Here VM goes to the subnet which has IP 10.2.2.10


Wednesday, February 11, 2015

Get all Open Patchset of particular Project from review.openstack.org

OpenStack what is the difference between driver and plugin


a)
Driver is a minimal implementation and Plugin is a complete specific implementation.

b)
Every driver will have a plugin, right ?

yeah, pretty much, although there are a couple of drivers / agents that use the ML2 plugin. So, it's not a 1-to-1 link

c)
Driver - Example ML2 Drivers . - ML2 is a plugin with the core implementation. All the Driver use a the results of core implementation.

Plugin - Example vmware, ml2, cisco, mlnx etc .. - Refer to individual specific implementation of a core abstract.

Sunday, February 1, 2015

OpenStack oslo messaging and config examples

* How to print configuration using oslo.config

from pprint import pprint
from oslo.config import cfg

res = [{k:v} for k, v in cfg.CONF.iteritems()]
pprint(res)


==============

* How to register/unregister/override an option in configuration using oslo.config


from pprint import pprint
from oslo.config import cfg

##Register
opts = [cfg.StrOpt('api_server_ip', default='127.0.0.1', help=""),]
cfg.CONF.register_opts(opts)
OR
cfg.CONF.register_opt(cfg.StrOpt('api_server_ip', default='127.0.0.1', help=""))

##Unregister
opts = [cfg.StrOpt('api_server_ip', default='127.0.0.1', help=""),]
cfg.CONF.unregister_opts(opts)
OR
cfg.CONF.unregister_opt(cfg.StrOpt('api_server_ip', default='127.0.0.1', help=""))

##Override
cfg.CONF.set_override('transport_url', None)

##Print
res = [{k:v} for k, v in cfg.CONF.iteritems()]
pprint(res)






==============

* RPC Server
--------------------


#vim /usr/local/lib/python2.7/dist-packages/oslo.messaging-1.4.1.dist-info/entry_points.txt

from pprint import pprint
from oslo.config import cfg
import oslo.messaging as om

##Invoke "get_transport". This call will set default Configurations required to Create Messaging Transport
>>> transport = om.get_transport(cfg.CONF)

##Set/Override Configurations required to Create Messaging Transport
cfg.CONF.set_override('rabbit_host', '127.0.0.1')
cfg.CONF.set_override('rabbit_port', 5672)
cfg.CONF.set_override('rabbit_userid', 'guest')
cfg.CONF.set_override('rabbit_password', 'cloud')
cfg.CONF.set_override('rabbit_login_method', 'AMQPLAIN')
cfg.CONF.set_override('rabbit_virtual_host', '/')
cfg.CONF.set_override('rpc_backend', 'rabbit')

##Check Configurations
res = [{k:v} for k, v in cfg.CONF.iteritems()]
pprint(res)

##Create Messaging Transport
>>> transport = om.get_transport(cfg.CONF)

##Set/Override Configurations required to Create Target (Exchange, Topic and Server to listen on)
>>> cfg.CONF.set_override('control_exchange', 'openstack')

##Create Target (Exchange, Topic and Server to listen on)
>>> target = om.Target(topic='testme', server='127.0.0.1')

>>> target.namespace
>>> target.topic
'testme'
>>> target.version
>>> target.fanout
>>> target.server
'127.0.0.1'
>>> target.exchange

##Create End Points
class TestEndpoint(object):
    def test(self, ctx, arg):
        return arg

endpoints = [TestEndpoint(),]

##Create RPC Server
server = om.get_rpc_server(transport, target, endpoints, executor='blocking')

>>> server.dispatcher

>>> server.transport

>>> server.executor
'blocking'
>>> server.start
>
>>>

##Check rabbitmq queue
#sudo rabbitmqctl list_queues | grep testme
testme    0
testme.127.0.0.1    0
testme_fanout_ba1e644ad10e40fc881793445b5e42bf    0

##Debug RPC server
#vim /usr/local/lib/python2.7/dist-packages/oslo/messaging/server.py
Add debug statement "import pdb; pdb.set_trace()" in method "start".
   

* RPC Client
------------------


from pprint import pprint
from oslo.config import cfg
import oslo.messaging as om

##Invoke "get_transport". This call will set default Configurations required to Create Messaging Transport
>>> transport = om.get_transport(cfg.CONF)

##Set Configurations required to Create Messaging Transport

cfg.CONF.set_override('rabbit_host', '127.0.0.1')
cfg.CONF.set_override('rabbit_port', 5672)
cfg.CONF.set_override('rabbit_userid', 'guest')
cfg.CONF.set_override('rabbit_password', 'cloud')
cfg.CONF.set_override('rabbit_login_method', 'AMQPLAIN')
cfg.CONF.set_override('rabbit_virtual_host', '/')
cfg.CONF.set_override('rpc_backend', 'rabbit')

##Check Configurations
res = [{k:v} for k, v in cfg.CONF.iteritems()]
pprint(res)

##Create Messaging Transport
>>> transport = om.get_transport(cfg.CONF)

##Create Target
>>> target = om.Target(topic='testme')

##Create RPC Client
>>> client = om.RPCClient(transport, target)

##Invoke remote method named "test"

ctxt={}
arg="blabla"
client.call(ctxt, 'test', arg=arg)

==============

RPC Server Code
-----------------------


from pprint import pprint
from oslo.config import cfg
import oslo.messaging as om

##Invoke "get_transport". This call will set default Configurations required to Create Messaging Transport
transport = om.get_transport(cfg.CONF)

##Set/Override Configurations required to Create Messaging Transport
cfg.CONF.set_override('rabbit_host', '127.0.0.1')
cfg.CONF.set_override('rabbit_port', 5672)
cfg.CONF.set_override('rabbit_userid', 'guest')
cfg.CONF.set_override('rabbit_password', 'cloud')
cfg.CONF.set_override('rabbit_login_method', 'AMQPLAIN')
cfg.CONF.set_override('rabbit_virtual_host', '/')
cfg.CONF.set_override('rpc_backend', 'rabbit')

##Check Configurations
res = [{k:v} for k, v in cfg.CONF.iteritems()]
pprint(res)

##Create Messaging Transport
transport = om.get_transport(cfg.CONF)

##Create Target (Exchange, Topic and Server to listen on)
target = om.Target(topic='testme', server='10.0.2.15')

##Create End Points
class TestEndpoint(object):
    def test_method1(self, ctx, arg):
        res = "Result from test_method1 " + str(arg)
        print res
        return res
    def test_method2(self, ctx, arg):
        res = "Result from test_method2 " + str(arg)
        print res
        return res

endpoints = [TestEndpoint(),]


##Create RPC Server
server = om.get_rpc_server(transport, target, endpoints, executor='blocking')

##Start RPC Server
server.start()

RPC Client Code
-----------------------


from pprint import pprint
from oslo.config import cfg
import oslo.messaging as om

##Invoke "get_transport". This call will set default Configurations required to Create Messaging Transport
transport = om.get_transport(cfg.CONF)

##Set Configurations required to Create Messaging Transport
cfg.CONF.set_override('rabbit_host', '127.0.0.1')
cfg.CONF.set_override('rabbit_port', 5672)
cfg.CONF.set_override('rabbit_userid', 'guest')
cfg.CONF.set_override('rabbit_password', 'cloud')
cfg.CONF.set_override('rabbit_login_method', 'AMQPLAIN')
cfg.CONF.set_override('rabbit_virtual_host', '/')
cfg.CONF.set_override('rpc_backend', 'rabbit')

##Check Configurations
res = [{k:v} for k, v in cfg.CONF.iteritems()]
pprint(res)

##Create Messaging Transport
transport = om.get_transport(cfg.CONF)

##Create Target
target = om.Target(topic='testme', server='10.0.2.15')

##Create RPC Client
client = om.RPCClient(transport, target)

##Invoke remote method and wait for a reply.
arg = "Saju"
ctxt = {}
client.call(ctxt, 'test_method1', arg=arg)

##Invoke remote method and return immediately.
arg = "Saju"
ctxt = {}
client.cast(ctxt, 'test_method1', arg=arg)

==============

a)
Client Request to Specific Server

##Create Target
target = om.Target(topic='testme', server='127.0.0.1')
##Create RPC Client
client = om.RPCClient(transport, target)
for x in range(10):
    client.call(ctxt, 'test_method1', arg=x)

b)
Client Request to one of the servers in a round-robin fashion.

##Create Target
target = om.Target(topic='testme')
##Create RPC Client
client = om.RPCClient(transport, target)
for x in range(10):
    client.call(ctxt, 'test_method1', arg=x)

b)
Client Request to all the servers. (fanout)

##Create Target
target = om.Target(topic='testme')
##Create RPC Client
client = om.RPCClient(transport, target, fanout=True)
for x in range(10):
    client.call(ctxt, 'test_method1', arg=x)

Thursday, January 29, 2015

How to OpenStack load Drivers Extensions and Plugins using stevedore

1)
Create a virtual environment

#virtualenv venv
#source venv/bin/activate




2)
Install stevedore
#pip install stevedore

3)
Open Python console

#python
>>> from stevedore import driver
>>> p=driver.DriverManager(namespace="stevedore.example.formatter", name='simple')


* Means, load the driver "simple" from then namespace "stevedore.example.formatter"".

* "namespace" is defined in setup.py as "entry_points".
https://github.com/openstack/stevedore/blob/master/stevedore/example/setup.py

* Driver file "simple"
https://github.com/openstack/stevedore/blob/master/stevedore/example/simple.py

* For more info
http://docs.openstack.org/developer/stevedore/tutorial/creating_plugins.html

4)
"entry_points" from neutron project.
https://github.com/openstack/neutron/blob/master/setup.cfg

==== Custom Example=======

1)
Create a new project named "myproject" and create following files


a)
#setup.py


import setuptools
setuptools.setup(setup_requires=['pbr'], pbr=True)


b)

#setup.cfg

[metadata]
name = myproject

[files]
packages = myproject

[entry_points]
myproject.driver =
    simple_driver1 = myproject.my_driver:SimpleDriver1
    simple_driver2 = myproject.my_driver:SimpleDriver2

myproject.extension =
    simple_extension1 = myproject.my_extension:SimpleExtension1
    simple_extension2 = myproject.my_extension:SimpleExtension2


c)
Inside the "myproject" directory create an another directory with same name
and create following "my_driver.py" and "my_extension.py" files in it.

#mkdir myproject
#cd  myproject

d)
#vim my_driver.py


class SimpleDriver1:

    def get_name(self):
        return "This is SimpleDriver1"

class SimpleDriver2:

    def get_name(
self):
        return "This is SimpleDriver2"

      
e)
#vim my_extension.py


class SimpleExtension1:

    def get_name(
self):
        return "This is SimpleExtension1"

class SimpleExtension2:

    def get_name(
self):
        return "This is SimpleExtension2"


2)
Create a virtual environment

#virtualenv venv
#source venv/bin/activate


3)

Install stevedore
#pip install stevedore
     
4)
Goto "myproject" directory and install the project/module using setup.py script.
#cd myproject
#git init    
#python setup.py install    
  
      
5)
Goto python console, import stevedore and load the drivers and extensions from "myproject" module.

a)
Load the driver named "simple_driver1" and invokes the method "get_name"

>>> from stevedore import driver
>>> mydriver = driver.DriverManager(namespace="myproject.driver", name='simple_driver1')
>>> mydriver.driver
>>> mydriver.driver().get_name()
OR
>>> mydriver.extensions[0].plugin().get_name()


b)
Load all the extensions from the namespace "myproject.extension"

>>> from stevedore import extension
>>> extension = extension.ExtensionManager(namespace="myproject.extension")
>>> extension.extensions
>>> extension.extensions[0].plugin().get_name()
>>> extension.extensions[1].plugin().get_name()



Tuesday, January 6, 2015

How to OpenStack Create Blueprint and Submit Patch Set

http://docs.openstack.org/training-guides/content/operator-getting-started-lab.html

https://wiki.openstack.org/wiki/Gerrit_Workflow

1)
* Install git and pip

#sudo apt-get install git
#sudo apt-get install python-pip




2)
* Install git-review

#sudo pip install git-review

3)
* Configure github


#git config -l

#git config --global user.name "Saju Madhavan"
#git config --global user.email "sajuptpm@gmail.com"
#git config --global core.editor "vim"

#git config -l


4)
Clone the project

#git clone https://github.com/openstack/neutron.git

5)
Goto project folder
#cd neutron

6)
* Test the ssh key setup


#git review -s
Enter your gerrit username: sajuptpm

7)
Goto Your Blueprint

https://blueprints.launchpad.net/neutron/+spec/opencontrail-ipam-extension

8)
Create a new git branch for your blueprint changes

#cd neutron
#git checkout -b blueprint/opencontrail-ipam-extension


9)
Confirm the branch

#git branch

11)
Make your changes and run unittest and pep8 test.


12)
Commit your changes

#git add file1 file2
#git commit -a


... commit message ...
....
....
Implements: blueprint opencontrail-ipam-extension

13)
Push changes to https://review.openstack.org

#git review

14)
Resubmit same patch after some modification
Run unit test and pep8 test.

#git commit -a --amend

15)
Push new changes to https://review.openstack.org

#git review

Monday, December 8, 2014

Setting Up OpenStack Python Client Development Environment

1)
Clone the Project

#git clone https://github.com/openstack/python-keystoneclient.git

2)
Goto cloned directory

#cd python-keystoneclient



3)
Setup the Environment


3,a)
With run_tests.sh

#./run_tests.sh

OR

3,b)
With tox

#sudo pip install tox
#tox

4)
Run the client commands


4,a)
With run_tests.sh Environment


4,a,a)Goto cloned directory
#cd python-keystoneclient

4,a,b)
Create a script named "keystone" with following statements in cloned directory.
#vim keystone

#!/usr/bin/python
# PBR Generated from 'console_scripts'
import sys
from keystoneclient.shell import main
if __name__ == "__main__":
    sys.exit(main())


4,a,c)
Run the keystone client commands from run_tests.sh Environment
#source .venv/bin/activate
#.venv/bin/python keystone tenant-list
#.venv/bin/python keystone user-list


OR

4,b)
With Tox Environment

4,b,a)
Goto cloned directory
#cd python-keystoneclient

4,b,b)
Create a script named "keystone" with following statements in cloned directory.
#vim keystone

#!/usr/bin/python
# PBR Generated from 'console_scripts'
import sys
from keystoneclient.shell import main
if __name__ == "__main__":
    sys.exit(main())


4,b,c)
Run the keystone client commands from Tox Environment
#source .tox/py27/bin/activate
#.tox/py27/bin/python keystone tenant-list
#.tox/py27/bin/python keystone user-list


5)
Run the Tests


5,a)
With run_tests.sh
#./run_tests.sh --debug keystoneclient.tests.v2_0.test_tenants.TenantTests.test_list

##Only pep8 test
#./run_tests.sh --debug --pep8 keystoneclient.tests.v2_0.test_tenants

##manual pep8 test with the wrapper flake8
#source .venv/bin/activate
#flake8 keystoneclient/tests/v2_0/test_tenants.py


OR

5,b)
With tox


* Deactivate virtualenv (Important), then run tox command , otherwise tox command will try to recreate the virtualenv from scratch
#deactivate

*UnitTest
#tox -e py27 -- keystoneclient.tests.v2_0.test_tenants.TenantTests.test_list
#tox -e py27 -- keystoneclient.tests.v2_0.test_tenants
#tox -e py27

*pep8 test
#tox -e pep8 -- keystoneclient.tests.v2_0.test_tenants
#tox -e pep8

http://fosshelp.blogspot.in/2014/11/openstack-unit-testing-tox-runtestssh.html







Thursday, December 4, 2014

OpenStack Debug Python Unit Test using pdb

1)
Add following statements in Unit Test Code where you want to debug

import pdb
pdb.set_trace()




2)
Run "run_tests.sh" with "--debug" option

#./run_tests.sh --debug neutron.tests.unit.opencontrail.test_extension_ipam.IpamExtensionTestCase.test_create_ipam

OR

Run the test with "testtools" instead of "testr"

a)
If you are using "run_tests.sh" environment
#source .venv/bin/activate
#.venv/bin/python -m testtools.run neutron.tests.unit.opencontrail.test_extension_ipam.IpamExtensionTestCase.test_create_ipam

b)
If you are using "Tox" environment
#source .tox/py27/bin/activate
#.tox/py27/bin/python -m testtools.run neutron.tests.unit.opencontrail.test_extension_ipam.IpamExtensionTestCase.test_create_ipam