Example #1
0
    def create_asterisk(self,
                        count=1,
                        base_configs_path=None,
                        test_config=None):
        """Create n instances of Asterisk

        Note: if the instances of Asterisk being created are remote, the
        keyword arguments to this function are ignored.

        Keyword arguments:
        count             The number of Asterisk instances to create.  Each
                          Asterisk instance will be hosted on 127.0.0.x, where x
                          is the 1-based index of the instance created.
        base_configs_path Provides common configuration for Asterisk instances
                          to use. This is useful for certain test types that use
                          the same configuration all the time. This
                          configuration can be overwritten by individual tests,
                          however.
        test_config       Test Configuration
        """
        for i, ast_config in enumerate(self.get_asterisk_hosts(count)):
            local_num = ast_config.get('num')
            host = ast_config.get('host')

            if not host:
                msg = "Cannot manage Asterisk instance without 'host'"
                raise Exception(msg)

            if local_num:
                LOGGER.info("Creating Asterisk instance %d" % local_num)
                ast_instance = Asterisk(base=self.testlogdir,
                                        host=host,
                                        ast_conf_options=self.ast_conf_options,
                                        test_config=test_config)
            else:
                LOGGER.info("Managing Asterisk instance at %s" % host)
                ast_instance = Asterisk(base=self.testlogdir,
                                        host=host,
                                        remote_config=ast_config,
                                        test_config=test_config)
            self.ast.append(ast_instance)
            self.condition_controller.register_asterisk_instance(self.ast[i])

            if local_num:
                # If a base configuration for this Asterisk instance has been
                # provided, install it first
                if base_configs_path is None:
                    base_configs_path = self.base_config_path
                if base_configs_path:
                    ast_dir = "%s/ast%d" % (base_configs_path, local_num)
                    self.ast[i].install_configs(ast_dir,
                                                self.test_config.get_deps())
                # Copy test specific config files
                self.ast[i].install_configs(
                    "%s/configs/ast%d" % (self.test_name, local_num),
                    self.test_config.get_deps())
    def __init__(self, api_url='http://localhost:8088/stasis'):
        """Initiate new AsteriskPy instance.

        Takes optional string api_url which points to the REST API base URL.
        Raise requests.exceptions

        """
        self._api_url = api_url
        self._api = AsteriskRestAPI(uri=self._api_url)
        self._asterisk = Asterisk(self._api)
    def create_asterisk(self, count=1, base_configs_path=None):
        """Create n instances of Asterisk

        Keyword arguments:
        count             The number of Asterisk instances to create.  Each
                          Asterisk instance will be hosted on 127.0.0.x, where x
                          is the 1-based index of the instance created
        base_configs_path Provides common configuration for Asterisk instances
                          to use. This is useful for certain test types that use
                          the same configuration all the time. This
                          configuration can be overwritten by individual tests,
                          however.
        """
        for i in range(count):
            num = i + 1
            LOGGER.info("Creating Asterisk instance %d" % num)
            host = "127.0.0.%d" % num
            self.ast.append(
                Asterisk(base=self.testlogdir,
                         host=host,
                         ast_conf_options=self.ast_conf_options))
            self.condition_controller.register_asterisk_instance(self.ast[i])
            # If a base configuration for this Asterisk instance has been
            # provided, install it first
            if base_configs_path:
                ast_dir = "%s/ast%d" % (base_configs_path, num)
                self.ast[i].install_configs(ast_dir,
                                            self.test_config.get_deps())
            # Copy test specific config files
            self.ast[i].install_configs(
                "%s/configs/ast%d" % (self.test_name, num),
                self.test_config.get_deps())
class AsteriskPy:
    """
    Python library for the Asterisk REST API.
    """
    def __init__(self, api_url='http://localhost:8088/stasis'):
        """Initiate new AsteriskPy instance.

        Takes optional string api_url which points to the REST API base URL.
        Raise requests.exceptions

        """
        self._api_url = api_url
        self._api = AsteriskRestAPI(uri=self._api_url)
        self._asterisk = Asterisk(self._api)

    def get_info(self):
        """Return dict of Asterisk system information"""
        return self._asterisk.get_info()

    def get_endpoints(self):
        """Return a list of all Endpoints from Asterisk."""
        result = self._api.call('endpoints', http_method='GET')
        # Temporary until method is implemented
        result_list = [Endpoint(self._api), Endpoint(self._api)]
        #endpoints = [Endpoint(x) for x in result]
        return result_list

    def get_channels(self):
        """Return a list of all Channels from Asterisk."""
        result = self._api.call('channels', http_method='GET')
        # Temporary until method is implemented
        result_list = [Channel(self._api), Channel(self._api)]
        #channels = [Channel(x) for x in result]
        return result_list

    def get_bridges(self):
        """Return a list of all Bridges from Asterisk"""
        result = self._api.call('bridges', http_method='GET')
        # Temporary until method is implemented
        result_list = [Bridge(self._api), Bridge(self._api)]
        #bridges = [Bridge(x) for x in result]
        return result_list

    def get_recordings(self):
        """Return a list of all Recordings from Asterisk."""
        result = self._api.call('recordings', http_method='GET')
        # Temporary until method is implemented
        result_list = [Recording(self._api), Recording(self._api)]
        #recordings = [Recording(x) for x in result]
        return result_list

    def get_endpoint(self, object_id):
        """Return Endpoint specified by object_id."""
        result = self._api.call('endpoints', http_method='GET',
                                object_id=object_id)
        # Temporary until method is implemented
        result = Endpoint(self._api)
        #endpoint = Endpoint(result)
        return result

    def get_channel(self, object_id):
        """Return Channel specified by object_id."""
        result = self._api.call('channels', http_method='GET',
                                object_id=object_id)
        # Temporary until method is implemented
        result = Channel(self._api)
        #channel = Channel(result)
        return result

    def get_bridge(self, object_id):
        """Return Bridge specified by object_id."""
        result = self._api.call('bridges', http_method='GET',
                                object_id=object_id)
        # Temporary until method is implemented
        result = Bridge(self._api)
        #bridge = Bridge(result)
        return result

    def get_recording(self, object_id):
        """Return Recording specified by object_id."""
        result = self._api.call('recordings', http_method='GET',
                                object_id=object_id)
        # Temporary until method is implemented
        result = Recording(self._api)
        #recording = Recording(result)
        return result

    def create_channel(self, params):
        """In Asterisk, originate a channel. Return the Channel."""
        result = self._api.call('channels', http_method='POST',
                                parameters=params)
        # Temporary until method is implemented
        result = Channel(self._api)
        return result

    def create_bridge(self, params):
        """In Asterisk, bridge two or more channels. Return the Bridge."""
        result = self._api.call('bridges', http_method='POST',
                                parameters=params)
        # Temporary until method is implemented
        result = Bridge(self._api)
        return result

    def add_event_handler(self, event_name, handler):
        """Add a general event handler for Stasis events.
        For object-specific events, use the object's add_event_handler instead.
        """
        pass

    def remove_event_handler(self, event_name, handler):
        """Add a general event handler for Stasis events.
        For object-specific events, use the object's add_event_handler instead.
        """
        pass
Example #5
0
class Dependency(object):
    """Class that checks and stores the dependencies for a particular Test."""

    try:
        asterisk_build_options = AsteriskBuildOptions()
    except:
        asterisk_build_options = None

    try:
        ast = Asterisk()
    except:
        ast = None

    def __init__(self, dep):
        """Construct a new dependency

        Keyword arguments:
        dep A tuple containing the dependency type name and its subinformation.
        """

        self.name = ""
        self.version = ""
        self.met = False
        if "app" in dep:
            self.name = dep["app"]
            self.met = test_suite_utils.which(self.name) is not None
        elif "python" in dep:
            self.name = dep["python"]
            try:
                __import__(self.name)
                self.met = True
            except ImportError:
                pass
        elif "sipp" in dep:
            self.name = "SIPp"
            version = None
            feature = None
            if 'version' in dep['sipp']:
                version = dep['sipp']['version']
            if 'feature' in dep['sipp']:
                feature = dep['sipp']['feature']
            self.sipp_version = SIPpVersion()
            self.version = SIPpVersion(version, feature)
            if self.sipp_version >= self.version:
                self.met = True
            if self.version.tls and not self.sipp_version.tls:
                self.met = False
            if self.version.pcap and not self.sipp_version.pcap:
                self.met = False
        elif "custom" in dep:
            self.name = dep["custom"]
            method = "depend_%s" % self.name
            found = False
            for dir_method in dir(self):
                if dir_method == method:
                    self.met = getattr(self, dir_method)()
                    found = True
            if not found:
                print "Unknown custom dependency - '%s'" % self.name
        elif "asterisk" in dep:
            if self.ast:
                self.name = dep["asterisk"]
                self.met = self._find_asterisk_module(self.name)
            else:
                # Remote Asterisk instance. Assume dependency is met
                self.met = True
        elif "buildoption" in dep:
            if self.ast:
                self.name = dep["buildoption"]
                self.met = self._find_build_flag(self.name)
            else:
                # Remote Asterisk instance. Assume dependency is met
                self.met = True
        elif "pcap" in dep:
            self.name = "pcap"
            from test_case import PCAP_AVAILABLE
            self.met = PCAP_AVAILABLE
        else:
            print "Unknown dependency type specified:"
            for key in dep.keys():
                print key

    def depend_remote(self):
        """Check to see if we run against a remote instance of Asterisk"""
        test_config = TestConfig(os.getcwd())
        if not test_config.config:
            return False
        if test_config.config.get('asterisk-instances'):
            return True
        return False

    def depend_soundcard(self):
        """Check the soundcard custom dependency"""
        try:
            dsp_file = open("/dev/dsp", "r")
            dsp_file.close()
            return True
        except:
            return False

    def depend_ipv6(self):
        """Check the ipv6 custom dependency"""
        try:
            test_sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
            test_sock.close()
            return True
        except:
            return False

    def depend_ipv4addr(self):
        """Check that an interface has a bindable ipv4 address (not loopback)
        """
        if test_suite_utils.get_bindable_ipv4_addr():
            return True
        return False

    def depend_ipv6addr(self):
        """Check that an interface has a bindable ipv6 address (not loopback,
           not link-local)
        """
        if test_suite_utils.get_bindable_ipv6_addr():
            return True
        return False

    def depend_pjsuav6(self):
        """This tests if pjsua was compiled with IPv6 support.

        To do this, we run pjsua --help and parse the output to determine if
        --ipv6 is a valid option
        """
        if test_suite_utils.which('pjsua') is None:
            return False

        help_output = subprocess.Popen(['pjsua', '--help'],
                                       stdout=subprocess.PIPE).communicate()[0]
        if help_output.find('--ipv6') == -1:
            return False
        return True

    def depend_fax(self):
        """Checks if Asterisk contains the necessary modules for fax tests"""
        fax_providers = [
            "app_fax",
            "res_fax_spandsp",
            "res_fax_digium",
        ]

        for fax in fax_providers:
            if self._find_asterisk_module(fax):
                return True

        return False

    def depend_rawsocket(self):
        """Check the raw socket custom dependency"""
        try:
            test_sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
            test_sock.close()
            return True
        except:
            return False

    def _find_build_flag(self, name):
        """Determine if the specified build option exists"""
        if self.asterisk_build_options:
            return (self.asterisk_build_options.check_option(name))
        else:
            print "Unable to evaluate build options: no build options found"
            return False

    def _find_asterisk_module(self, name):
        """Determine if an Asterisk module exists"""
        if not Dependency.ast:
            print "Unable to evaluate Asterisk modules: Asterisk not found"
            return False

        if Dependency.ast.original_astmoddir == "":
            return False

        module = "%s/%s.so" % (Dependency.ast.original_astmoddir, name)
        if os.path.exists(module):
            return True

        return False