from ops_nd.plugins.utils import execute
import ops_nd.log as logging
from ops_nd.options import get_options

LOG = logging.getLogger(__name__)

ovs_opts = [
    {
        "name": "",
        "default": "",
        "help": "",
        "type": str
    },
]
options = get_options(ovs_opts)


class PhysicalOperation(object):
    def __init__(self, ip, user, password):
        self.ip = ip
        self.user = user
        self.password = password

    def reset_machine(self):
        try:
            cmd = [
                "ipmitool", "-I", "lan", "-H", "{0}".format(self.ip), "-U",
                "{0}".format(self.user), "-P", "{0}".format(self.password),
                "power", "reset"
            ]
Beispiel #2
0
    {
        "name": 'sql_max_retries',
        "default": 10,
        "help": 'maximum db connection retries during startup. '
        '(setting -1 implies an infinite retry count)',
        "type": int,
    },
    {
        "name": 'sql_retry_interval',
        "default": 10,
        "help": 'interval between retries of opening a sql connection',
        "type": int,
    },
]

options = get_options(db_options, 'db')

_ENGINE = None
_MAKER = None


def get_session(autocommit=True, expire_on_commit=False):
    """Return a SQLAlchemy session."""
    global _MAKER

    if _MAKER is None:
        engine = get_engine()
        _MAKER = get_maker(engine, autocommit, expire_on_commit)

    session = _MAKER()
    session.query = exception.wrap_db_error(session.query)
Beispiel #3
0
# encoding=utf-8
import json

import ops_nd.log as logging
from ops_nd.options import get_options
from ops_nd.utils import get_http, post_http, put_http
from ops_nd.plugins.openstack_handle import OpenStackHandle

LOG = logging.getLogger(__name__)

cmdb_opts = [
]
options = get_options(cmdb_opts)


class CMDBHandle(object):
    @staticmethod
    def get_physical_info(cmdb_uuid):
        try:
            admin_token = OpenStackHandle.get_token()
            url = options.cmdb_ep + "/assets/" + cmdb_uuid
            headers = {'X-Auth-Token': admin_token.strip()}
            ret = get_http(url=url, headers=headers)
            if ret.status_code != 200:
                em = "get physical info from cmdb error...."
                LOG.exception(em)
                return False, ret.status_code
            return ret.json()["property"]
        except Exception as e:
            em = "get physical info from cmdb error. msg: <{0}>".format(e)
            LOG.exception(em)
Beispiel #4
0
level(LinuxNetDriver vs CiscoNetDriver).

Managers will often provide methods for initial setup of a host or periodic
tasks to a wrapping service.

This module provides Manager, a base class for managers.

"""
import socket
import eventlet

from ops_nd import utils
from ops_nd import log as logging
from ops_nd.options import get_options

options = get_options()

LOG = logging.getLogger(__name__)


def periodic_task(*args, **kwargs):
    """Decorator to indicate that a method is a periodic task.

    This decorator can be used in two ways:

        1. Without arguments '@periodic_task', this will be run on every tick
           of the periodic scheduler.

        2. With arguments, @periodic_task(ticks_between_runs=N), this will be
           run on every N ticks of the periodic scheduler.
    """
Beispiel #5
0
    },
    {
        "name": 'log_date_format',
        "default": '%Y-%m-%d %H:%M:%S',
        "help": 'time format of log',
        "type": str,
    },
    {
        "name": 'logfile_mode',
        "default": '0644',
        "help": 'Default file mode used when creating log files',
        "type": str,
    },
]

options = get_options(service_opts, 'services')

# our new audit level
# NOTE(jkoelker) Since we synthesized an audit level, make the logging
#                module aware of it so it acts like other levels.
logging.AUDIT = logging.INFO + 1
logging.addLevelName(logging.AUDIT, 'AUDIT')

try:
    NullHandler = logging.NullHandler
except AttributeError:  # NOTE(jkoelker) NullHandler added in Python 2.7

    class NullHandler(logging.Handler):
        def handle(self, record):
            pass
Beispiel #6
0
from ops_nd.options import get_options

auth_opts = [{
    "name": "cached_backend",
    "default": 'redis://127.0.0.1:6379/0',
    "help": 'cached backend uri',
    "type": str,
}, {
    "name": 'cache_timeout',
    "default": '3600',
    "help": 'cache timeout seconds',
    "type": str,
}]

options = get_options(auth_opts, 'cache')


class Backend(object):
    def __init__(self):
        cached_backend = options.cached_backend
        _conn = cached_backend.split("//")[1]
        if '@' in _conn:
            passwd, host_port = _conn.split('@')
        else:
            passwd = None
            host_port = _conn
        if passwd:
            passwd = passwd[1:]
        host, db_p = host_port.split(':')
        port, db = db_p.split('/')
import ops_nd.log as logging
from ops_nd.options import get_options
from ops_nd.utils import get_http, post_http
from ops_nd.plugins.openstack_handle import OpenStackHandle

LOG = logging.getLogger(__name__)

vp_opts = [
    {"name": "vp_network_ep",
     "default": "http://10.200.100.35:8913/api/v1.0/networks",
     "help": "get virtual&physical network",
     "type": str
     },

]
options = get_options(vp_opts)


class VPHandle(object):
    @staticmethod
    def get_network_info(network_uuid, token):
        try:
            headers = {'X-Auth-Token': token.strip()}
            ret = get_http(url=options.vp_network_ep, headers=headers)
            if ret.status_code != 200:
                em = "get network info error...."
                LOG.exception(em)
                return False, ret.status_code
            nets = ret.json()["networks"]
            for net in nets:
                if net.get("id") == network_uuid:
Beispiel #8
0
from ops_nd import cache
from ops_nd import utils
from ops_nd import log as logging

from ops_nd.service import db as service_db

auth_opts = [
    {
        "name": "policy",
        "default": "ops_nd.api.auth.policy",
        "help": "",
        "type": str,
    },
]

options = get_options(auth_opts, 'auth')

LOG = logging.getLogger()


def load_policy():
    option_split = options.policy.split(".")
    mod = option_split[0]
    fun = options.policy[options.policy.rfind('.') + 1:]
    fn_, modpath, desc = imp.find_module(mod)
    fn_, path, desc = imp.find_module(
        fun, [os.path.join(modpath, "/".join(option_split[1:-1]))])
    return imp.load_module(fun, fn_, path, desc)


class BaseAuth(tornado.web.RequestHandler):
Beispiel #9
0
from sqlalchemy import Column, Integer, BigInteger, String, schema
from sqlalchemy import ForeignKey, DateTime, Boolean, Text, Float

from ops_nd import options
from ops_nd.db.models import BASE
from ops_nd.db.session import register_models

options = options.get_options()


class CostLog(BASE):
    '''
    status:
        active: the instance is in use, means it's stilling billing
        deleted: the instance is deleted; means it's already settlement
    '''
    __tablename__ = 'cost_log'
    id = Column(Integer, primary_key=True, autoincrement=True)
    tenant_id = Column(String(255))
    user_id = Column(String(255))
    cost = Column(Float, nullable=False, default=0)
    unit = Column(Float, nullable=False, default=0)
    status = Column(String(255), nullable=False, default='active')


register_models((CostLog, ))
Beispiel #10
0
# -*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText

from ops_nd.options import get_options


smtp_options = [
    {
        "name": "smtp_uri",
        "default": "smtp://*****:*****@smtp_server:smtp_port",
        "help": "smtp auth info",
        "type": str,
    }]

options = get_options(smtp_options)

def send_mail(to_list,sub,content,html=False):
    smtp = options.smtp_uri
    mail_postfix = "gamewave.net"
    mail_host = smtp.split("@")[-1].split(":")[0]
    mail_user = smtp.split(":")[1].split("/")[-1]
    mail_pass = smtp.split("@")[0].split(":")[-1]
    me="AlertCenter"+"<"+mail_user+"@"+mail_postfix+">"
    if html:
        msg = MIMEText(content,_subtype='html',_charset='utf-8')
    else:
        msg = MIMEText(content,_charset='utf-8')
    msg['Subject'] = sub
    msg['From'] = me
    msg['To'] = ";".join(to_list)
Beispiel #11
0
    {
        "name": "sdn_sw_ep",
        # "default": "http://10.200.100.35:8913/api/v1.0/switch/sdn",
        "default": "http://10.200.100.35:8913/api/v1.0/switch/sdn",
        "help": "sdn switch end point",
        "type": str
    },
    {
        "name": "l2_sw_ep",
        # "default": "http://10.200.100.35:8913/api/v1.0/switch/l2switch",
        "default": "http://10.200.100.35:8913/api/v1.0/switch/l2switch",
        "help": "layer 2 switch end point",
        "type": str
    },
]
options = get_options(sw_opts)


class L2SwitchConfig(object):
    @staticmethod
    def sw_delete_port(network_id, sw_ip, sw_password, sw_username, token,
                       sw_port):
        try:
            # set l2 switch port to access 4094
            data = {
                "network_id": network_id,
                "sw_ip": sw_ip,
                "sw_pwd": sw_password,
                "sw_user": sw_username,
                "sw_port": sw_port
            }