Esempio n. 1
0
import sys
import errno
from pathlib import Path
import random
import re
import functools
import tempfile
import struct

from virtualbricks import log

from twisted.internet import utils
from twisted.python import constants

logger = log.Logger()
ksm_error = log.Event("Can not change ksm state. (failed command: {cmd})")


def random_mac():
    random.seed()
    return "00:aa:{0:02x}:{1:02x}:{2:02x}:{3:02x}".format(
        random.getrandbits(8), random.getrandbits(8), random.getrandbits(8),
        random.getrandbits(8))

RandMac = random_mac
MAC_RE = re.compile(r"^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$")


def mac_is_valid(mac):
    return bool(MAC_RE.match(mac))
Esempio n. 2
0
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

from twisted.internet import reactor, defer

from virtualbricks import base, errors, console, log

if False:  # pyflakes
    _ = str

process_ended = log.Event("Process ended with exit code {code}")
event_error = log.Event("Error in event action. See the log for more "
                        "informations")


class Command(base.String):
    def from_string(self, in_object):
        if in_object.startswith("add "):
            factory = console.VbShellCommand
        elif in_object.startswith("addsh "):
            factory = console.ShellCommand
        else:
            raise RuntimeError()
        return factory(in_object.split(" ", 1)[1])

    def to_string(self, in_object):
Esempio n. 3
0
        for name, param in sorted(self.config.parameters.iteritems()):
            if self.config[name] != param.default:
                value = param.to_string_brick(self.config[name], self)
                l.append(opt_tmp.format(name, value))
        if l:
            l.append("")
        tmp = "[{0}:{1}]\n{2}\n"
        fileobj.write(tmp.format(self.get_type(), self.name, "\n".join(l)))


if False:  # pyflakes
    _ = str

__metaclass__ = type
logger = log.Logger()
attribute_set = log.Event("Attribute {attr} set in {brick} with value "
                          "{value}.")
param_not_found = log.Event("Parameter {param} in {brick} not found. "
                            "(val: {value})")


class Config(dict):

    CONFIG_LINE = re.compile(r"^(\w+?)=(.*)$")
    parameters = {}

    def __init__(self):
        parameters = {}
        reflect.accumulateClassDict(self.__class__, "parameters", parameters)
        self.parameters = parameters
        iterFixItem(self)
Esempio n. 4
0
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import os
import textwrap

from twisted.internet import interfaces, utils
from twisted.protocols import basic
from zope.interface import implementer

from virtualbricks import __version__, bricks, errors, log, settings


logger = log.Logger()
socket_error = log.Event("Error on socket")
qemu_not_vde = log.Event("Qemu but not VDE plug")
invalid_brick = log.Event("Not a Qemu Plug")
conn_ok = log.Event("Connection ok")
conn_failed = log.Event("Connection failed")
quit_loop = log.Event("Quitting command loop")

if False:  # pyflakes
    _ = str


class _Error(Exception):
    """Please don't use."""


class String(str):
Esempio n. 5
0
from twisted.python import filepath
from zope.interface import implementer

from virtualbricks import interfaces, settings, configparser, log

if False:  # pyflakes
    _ = str

__all__ = [
    "BrickBuilder", "ConfigFile", "EventBuilder", "ImageBuilder",
    "LinkBuilder", "SockBuilder", "log_events", "restore", "safe_save", "save"
]

logger = log.Logger()
link_type_error = log.Event("Cannot find link of type {type}")
brick_not_found = log.Event("Cannot find brick {brick}, skipping line {line}")
sock_not_found = log.Event("Cannot find sock {sockname}, skipping line {line}")
link_added = log.Event("Added {type} to {brick}")
cannot_save_backup = log.Event("Cannot save to backup file {filename}.\n"
                               "{traceback}")
project_saved = log.Event("Saved project to {filename}.")
cannot_restore_backup = log.Event("Cannot restore backup file {filename}.\n"
                                  "{traceback}")
backup_restored = log.Event("A backup file for the current project has been "
                            "restored.\nYou can find more informations "
                            "looking in View->Messages.")
image_found = log.Event("Found Disk image {name}")
skip_image = log.Event("Skipping disk image, name '{name}' already in use")
skip_image_noa = log.Event("Cannot access image file, skipping")
config_dump = log.Event("CONFIG DUMP on {path}")
Esempio n. 6
0
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import os

from virtualbricks import bricks, link, log
from virtualbricks._spawn import abspath_vde


logger = log.Logger()
pwdgen_exit = log.Event("Command pwdgen exited with {code}")

if False:  # pyflakes
    _ = str


class TunnelListenConfig(bricks.Config):

    parameters = {"password": bricks.String(""),
                  "port": bricks.SpinInt(7667, 1, 65535)}


class TunnelListen(bricks.Brick):

    type = "TunnelListen"
    config_factory = TunnelListenConfig
Esempio n. 7
0
import os
import errno
import itertools
import re

from twisted.internet import utils, error, defer
from twisted.python import filepath

from virtualbricks import (settings, configfile, log, errors, configparser,
                           tools)


logger = log.Logger()
__metaclass__ = type

create_archive = log.Event("Create archive in {path}")
extract_archive = log.Event("Extract archive in {path}")
open_project = log.Event("Restoring project {name}")
import_project = log.Event("Importing project from {path} as {name}")
create_project = log.Event("Create project {name}")
write_project = log.Event("Writing new .project file")
rebase_error = log.Event("Error on rebase")
rebase = log.Event("Rebasing {cow} to {basefile}")
remap_image = log.Event("Mapping {original} to {new}")
extract_project = log.Event("Extracting project")
cannot_find_project = log.Event("Cannot find project \"{name}\". "
                                "A new project will be created.")
include_images = log.Event("Including the following images to the project: "
                           "{images}.")
save_images = log.Event("Move virtual machine's images")
DEFAULT_PROJECT_RE = re.compile(r"^{0}(?:_\d+)?$".format(
Esempio n. 8
0
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import traceback

from zope.interface import Interface, Attribute
from twisted.python.components import registerAdapter

from virtualbricks import log

__all__ = ["registerAdapter", "InterfaceLogger", "IBrick", "IPlug", "IBuilder"]

logger = log.Logger()
non_interface = log.Event("Requested a non-interface ({interface}) method: "
                          "{method}\n{traceback}")


class InterfaceLogger:
    def __init__(self, original, interface):
        self.original = original
        self.interface = interface

    def __getattr__(self, name):
        if name not in self.interface:
            tb = lambda: "\n".join("{0}:{1} {2}".format(fn, l, fun)
                                   for fn, l, fun, t in reversed(
                                       traceback.extract_stack()))
            logger.warn(non_interface,
                        interface=self.interface.__name__,
                        method=name,
Esempio n. 9
0
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

from collections import OrderedDict
import os

from twisted.internet import defer

from virtualbricks import settings, bricks, log, errors
from virtualbricks._spawn import abspath_vde

if False:  # pyflakes
    _ = str

sock_not_exists = log.Event("Socket does not exists: {path}")


class SwitchConfig(bricks.Config):

    parameters = {
        "numports": bricks.SpinInt(32, 1, 128),
        "hub": bricks.Boolean(False),
        "fstp": bricks.Boolean(False)
    }


class Switch(bricks.Brick):

    type = "Switch"
    ports_used = 0
Esempio n. 10
0
from virtualbricks import base, errors, settings, log, interfaces
from virtualbricks.base import (Config as _Config, Parameter, String, Integer,
                                SpinInt, Float, SpinFloat, Boolean, Object,
                                ListOf)
from virtualbricks._spawn import abspath_vde

__all__ = [
    "Brick", "Config", "Parameter", "String", "Integer", "SpinInt", "Float",
    "SpinFloat", "Boolean", "Object", "ListOf"
]

if False:  # pyflakes
    _ = str

logger = log.Logger(__name__)
process_started = log.Event("Process started")
process_terminated = log.Event("Process terminated. {status()}")
process_done = log.Event("Process terminated")
event_unavailable = log.Event("Warning. The Event {name} attached to Brick "
                              "{brick} is not available. Skipping execution.")
shutdown_brick = log.Event("Shutting down {name} (pid: {pid})")
start_brick = log.Event("Starting: {args()}")
open_console = log.Event("Opening console for {name}\n%{args()}\n")
console_done = log.Event("Console terminated\n{status}")
console_terminated = log.Event("Console terminated\n{status}\nProcess stdout:"
                               "\n{out()}\nProcess stderr:\n{err()}\n")
invalid_ack = log.Event("ACK received but no command sent.")


class ProcessLogger(object):
    def __init__(self, logger):
Esempio n. 11
0
from twisted.conch.insults import insults
from twisted.conch import manhole

from virtualbricks import errors, settings, configfile, console, project, log
from virtualbricks import events, link, router, switches, tunnels, tuntaps
from virtualbricks import virtualmachines, wires
from virtualbricks.virtualmachines import is_virtualmachine
from virtualbricks import observable
from virtualbricks.tools import is_running


if False:  # pyflakes
    _ = str

logger = log.Logger()
reg_basic_types = log.Event("Registering basic types")
engine_bye = log.Event("Engine: Bye!")
reg_new_type = log.Event("Registering new brick type {type}")
type_present = log.Event("Type {type} already present, overriding it")
create_image = log.Event("Creating new disk image at '{path}'")
remove_socks = log.Event("Removing socks: {socks}")
disconnect_plug = log.Event("Disconnecting plug to {sock}")
remove_brick = log.Event("Removing brick {brick}")
endpoint_not_found = log.Event("Endpoint {nick} not found.")
shut_down = log.Event("Server Shut Down.")
new_event_ok = log.Event("New event {name} OK")
uncaught_exception = log.Event("Uncaught exception: {error()}")
brick_stop = log.Event("Error on brick poweroff")


def install_brick_types(registry=None):
Esempio n. 12
0
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import os
import ConfigParser

from virtualbricks import tools, log
from virtualbricks.errors import NoOptionError

if False:  # pyflakes
    _ = str

logger = log.Logger()
config_loaded = log.Event("Configuration loaded ({filename})")
config_installed = log.Event("Default configuration saved ({filename})")
cannot_read_config = log.Event("Cannot read config file {filename}")
cannot_save_config = log.Event("Cannot save default configuration")

LOCK_FILE = "/tmp/vb.lock"
HOME = os.path.expanduser("~")
VIRTUALBRICKS_HOME = os.path.join(HOME, ".virtualbricks")
CONFIGFILE = os.path.join(HOME, ".virtualbricks.conf")
DEFAULT_WORKSPACE = VIRTUALBRICKS_HOME
DEFAULT_PROJECT = "new_project"
DEFAULT_CONF = {
    "term": "/usr/bin/xterm",
    "alt-term": "/usr/bin/gnome-terminal",
    "sudo": "/usr/bin/gksu",
    "kvm": False,
Esempio n. 13
0
import os

from twisted.internet import defer

from virtualbricks import errors, settings, log


if False:  # pyflakes
    _ = str


__metaclass__ = type

link_loop = log.Event("Loop link detected: aborting operation. If you want "
                      "to start a looped network, disable the check loop "
                      "feature in the general settings")


class Plug:

    sock = None
    _antiloop = False
    mode = "vde"
    logger = log.Logger()
    model = ""
    mac = ""

    def __init__(self, brick):
        self.brick = brick
Esempio n. 14
0
import logging

import twisted
from twisted.trial import unittest
from twisted.python import log as legacylog

from virtualbricks import log
from virtualbricks.tests import skipUnless


logger = log.Logger()
test_event = log.Event("This is a test event")
test_event_2 = log.Event("This is another test event")


class Observer(list):

    def __call__(self, event):
        self.append(event)

    def __hash__(self):
        return object.__hash__(self)


def install_observer(test_case):
    observer = Observer()
    logger.publisher.addObserver(observer)
    test_case.addCleanup(logger.publisher.removeObserver, observer)
    return observer

Esempio n. 15
0
import shutil
import itertools

from twisted.internet import utils, defer

from virtualbricks import (errors, tools, settings, bricks, log, project,
                           observable)
from virtualbricks._spawn import getQemuOutputAndValue, abspath_qemu


if False:
    _ = str

__metaclass__ = type
logger = log.Logger()
new_cow = log.Event("Creating a new private COW from {base} image.")
invalid_base = log.Event("{cowname} private cow found with a different base "
                         "image ({base}): moving it in {path}")
powerdown = log.Event("Sending powerdown to {vm}")
update_usb = log.Event("update_usbdevlist: old {old} - new {new}")
own_err = log.Event("plug {plug} does not belong to {brick}")
acquire_lock = log.Event("Aquiring disk locks")
release_lock = log.Event("Releasing disk locks")


class UsbDevice:

    def __init__(self, ID, desc=""):
        self.ID = ID
        self.desc = desc