Exemple #1
0
    def perspective_persist(self, profile='jcli-prod'):
        path = '%s/%s.smppccs' % (self.config.store_path, profile)
        self.log.info(
            'Persisting current configuration to [%s] profile in %s' %
            (profile, path))

        try:
            # Prepare connectors for persistence
            # Will persist config and service status only
            connectors = []
            for c in self.connectors:
                connectors.append({
                    'id': c['id'],
                    'config': c['config'],
                    'service_status': c['service'].running
                })

            # Write configuration with datetime stamp
            fh = open(path, 'w')
            fh.write('Persisted on %s [Jasmin %s]\n' %
                     (time.strftime("%c"), jasmin.get_release()))
            fh.write(pickle.dumps(connectors, self.pickleProtocol))
            fh.close()

            # Set persistance state to True
            self.persisted = True
        except IOError:
            self.log.error('Cannot persist to %s' % path)
            return False
        except Exception, e:
            self.log.error(
                'Unknown error occurred while persisting configuration: %s' %
                e)
            return False
Exemple #2
0
    def perspective_persist(self, profile = 'jcli-prod'):
        path = '%s/%s.smppccs' % (self.config.store_path, profile)
        self.log.info('Persisting current configuration to [%s] profile in %s' % (profile, path))
        
        try:
            # Prepare connectors for persistence
            # Will persist config and service status only
            connectors = []
            for c in self.connectors:
                connectors.append({'id': c['id'], 
                                    'config': c['config'], 
                                    'service_status':c['service'].running})
            
            # Write configuration with datetime stamp
            fh = open(path,'w')
            fh.write('Persisted on %s [Jasmin %s]\n' % (time.strftime("%c"), jasmin.get_release()))
            fh.write(pickle.dumps(connectors, self.pickleProtocol))
            fh.close()

            # Set persistance state to True
            self.persisted = True
        except IOError:
            self.log.error('Cannot persist to %s' % path)
            return False
        except Exception, e:
            self.log.error('Unknown error occurred while persisting configuration: %s' % e)
            return False
Exemple #3
0
    def getMigratedData(self):
        "Return data after executing migration steps"
        for m in MAP:
            # Context verification
            if self.context not in m['contexts']:
                self.log.debug('%s is not in map conditions: %s', self.context,
                               m['contexts'])
                continue

            # Validate conditions (with AND operator)
            valid = True
            for condition in m['conditions']:
                self.log.debug('Checking condition: %s with version %s',
                               condition, self.version)
                if not version_is_valid(self.version, condition):
                    self.log.debug('Condition failed: %s with version %s',
                                   condition, self.version)
                    valid = False
                    break

            # We have matching context and valid conditions
            if valid:
                for operation in m['operations']:
                    self.log.info(
                        'Migrating old data [%s] from v%s to v%s by calling %s(data)',
                        self.context, self.version, jasmin.get_release(),
                        operation.func_name)
                    self.data = operation(self.data)
        return self.data
Exemple #4
0
    def process_response(self, request, response, resource):
        """Force response to be json only and add Jasmin signature"""

        if response.content_type != 'application/json':
            response.content_type = 'application/json'

        if response.status[:3] == '200':
            response.body = json.dumps(response.body)

        # Add Jasmin signature
        if show_jasmin_version:
            response.set_header('Powered-By', 'Jasmin %s' % jasmin.get_release())
Exemple #5
0
    def persist(self, arg, opts):
        path = '%s/%s.filters' % (CONFIG_STORE_PATH, opts.profile)

        try:
            # Write configuration with datetime stamp
            fh = open(path, 'w')
            fh.write('Persisted on %s [Jasmin %s]\n' % (time.strftime("%c"), jasmin.get_release()))
            fh.write(pickle.dumps(self.filters, 2))
            fh.close()
        except IOError:
            return self.protocol.sendData('Cannot persist to %s' % path)
        except Exception, e:
            return self.protocol.sendData('Unknown error occurred while persisting configuration: %s' % e)
Exemple #6
0
 def persist(self, arg, opts):
     path = '%s/%s.filters' % (CONFIG_STORE_PATH, opts.profile)
     
     try:
         # Write configuration with datetime stamp
         fh = open(path,'w')
         fh.write('Persisted on %s [Jasmin %s]\n' % (time.strftime("%c"), jasmin.get_release()))
         fh.write(pickle.dumps(self.filters, 2))
         fh.close()
     except IOError:
         return self.protocol.sendData('Cannot persist to %s' % path)
     except Exception, e:
         return self.protocol.sendData('Unknown error occurred while persisting configuration: %s' % e)
    def test_auth_success(self):
        testPassword = '******' % random.randrange(100, 200)
        self.JCliConfigInstance.admin_password = md5(testPassword).digest()

        commands = [{
            'command': self.JCliConfigInstance.admin_username
        }, {
            'command':
            testPassword,
            'expect':
            'Welcome to Jasmin %s console' % jasmin.get_release(),
            'noecho':
            True
        }]
        return self._test(r'jcli : ', commands)
Exemple #8
0
    def setUp(self):
        yield jCliTestCases.setUp(self)

        # Connect to jCli server through a fake network transport
        self.JCliConfigInstance = JCliConfig()
        self.JCliConfigInstance.authentication = False
        self.JCli_f = JCliFactory(self.JCliConfigInstance, self.clientManager_f, self.RouterPB_f)
        self.proto = self.JCli_f.buildProtocol(('127.0.0.1', 0))
        self.tr = proto_helpers.StringTransport()
        self.proto.makeConnection(self.tr)
        # Test for greeting
        receivedLines = self.getBuffer(True)
        self.assertRegexpMatches(receivedLines[0], r'Welcome to Jasmin %s console' % jasmin.get_release())
        self.assertRegexpMatches(receivedLines[3], r'Type help or \? to list commands\.')
        self.assertRegexpMatches(receivedLines[9], r'Session ref: ')
Exemple #9
0
    def persist(self, arg, opts):
        path = '%s/%s.httpccs' % (CONFIG_STORE_PATH, opts.profile)

        try:
            # Write configuration with datetime stamp
            fh = open(path, 'w')
            fh.write('Persisted on %s [Jasmin %s]\n' % (time.strftime("%c"), jasmin.get_release()))
            fh.write(pickle.dumps(self.httpccs, pickle.HIGHEST_PROTOCOL))
            fh.close()
        except IOError:
            return self.protocol.sendData('Cannot persist to %s' % path)
        except Exception as e:
            return self.protocol.sendData('Unknown error occurred while persisting configuration: %s' % e)

        self.protocol.sendData(
            '%s configuration persisted (profile:%s)' % (self.managerName, opts.profile), prompt=False)
Exemple #10
0
    def persist(self, arg, opts):
        path = '%s/%s.filters' % (STORE_PATH, opts.profile)

        try:
            # Write configuration with datetime stamp
            fh = open(path, 'wb')
            fh.write(('Persisted on %s [Jasmin %s]\n' % (time.strftime("%c"), jasmin.get_release())).encode('ascii'))
            fh.write(pickle.dumps(self.filters, pickle.HIGHEST_PROTOCOL))
            fh.close()
        except IOError:
            return self.protocol.sendData('Cannot persist to %s' % path)
        except Exception as e:
            return self.protocol.sendData('Unknown error occurred while persisting configuration: %s' % e)

        self.protocol.sendData(
            '%s configuration persisted (profile:%s)' % (self.managerName, opts.profile), prompt=False)
Exemple #11
0
    def setUp(self):
        yield jCliTestCases.setUp(self)

        # Connect to jCli server through a fake network transport
        self.JCliConfigInstance = JCliConfig()
        self.JCliConfigInstance.authentication = False
        self.JCli_f = JCliFactory(self.JCliConfigInstance,
                                  self.clientManager_f, self.RouterPB_f)
        self.proto = self.JCli_f.buildProtocol(('127.0.0.1', 0))
        self.tr = proto_helpers.StringTransport()
        self.proto.makeConnection(self.tr)
        # Test for greeting
        receivedLines = self.getBuffer(True)
        self.assertRegexpMatches(
            receivedLines[0],
            r'Welcome to Jasmin %s console' % jasmin.get_release())
        self.assertRegexpMatches(receivedLines[3],
                                 r'Type help or \? to list commands\.')
        self.assertRegexpMatches(receivedLines[9], r'Session ref: ')
Exemple #12
0
    def getMigratedData(self):
        """Return data after executing migration steps"""
        for m in MAP:
            # Context verification
            if self.context not in m['contexts']:
                self.log.debug('%s is not in map conditions: %s', self.context, m['contexts'])
                continue

            # Validate conditions (with AND operator)
            valid = True
            for condition in m['conditions']:
                self.log.debug('Checking condition: %s with version %s', condition, self.version)
                if not version_is_valid(self.version, condition):
                    self.log.debug('Condition failed: %s with version %s', condition, self.version)
                    valid = False
                    break

            # We have matching context and valid conditions
            if valid:
                for operation in m['operations']:
                    self.log.info('Migrating old data [%s] from v%s to v%s by calling %s(data)',
                                  self.context, self.version, jasmin.get_release(), operation.func_name)
                    self.data = operation(self.data, context=self.context)
        return self.data
Exemple #13
0
    def test_version_release(self):
        yield self.connect('127.0.0.1', self.pbPort)

        version_release = yield self.version_release()

        self.assertEqual(version_release, jasmin.get_release())
Exemple #14
0
    def perspective_persist(self, profile="jcli-prod", scope="all"):
        try:
            if scope in ["all", "groups"]:
                # Persist groups configuration
                path = "%s/%s.router-groups" % (self.config.store_path, profile)
                self.log.info("Persisting current Groups configuration to [%s] profile in %s" % (profile, path))

                fh = open(path, "w")
                # Write configuration with datetime stamp
                fh.write("Persisted on %s [Jasmin %s]\n" % (time.strftime("%c"), jasmin.get_release()))
                fh.write(pickle.dumps(self.groups, self.pickleProtocol))
                fh.close()

                # Set persistance state to True
                self.persistenceState["groups"] = True

            if scope in ["all", "users"]:
                # Persist users configuration
                path = "%s/%s.router-users" % (self.config.store_path, profile)
                self.log.info("Persisting current Users configuration to [%s] profile in %s" % (profile, path))

                fh = open(path, "w")
                # Write configuration with datetime stamp
                fh.write("Persisted on %s [Jasmin %s]\n" % (time.strftime("%c"), jasmin.get_release()))
                fh.write(pickle.dumps(self.users, self.pickleProtocol))
                fh.close()

                # Set persistance state to True
                self.persistenceState["users"] = True
                for u in self.users:
                    u.mt_credential.quotas_updated = False

            if scope in ["all", "moroutes"]:
                # Persist moroutes configuration
                path = "%s/%s.router-moroutes" % (self.config.store_path, profile)
                self.log.info("Persisting current MORoutingTable to [%s] profile in %s" % (profile, path))

                fh = open(path, "w")
                # Write configuration with datetime stamp
                fh.write("Persisted on %s [Jasmin %s]\n" % (time.strftime("%c"), jasmin.get_release()))
                fh.write(pickle.dumps(self.mo_routing_table, self.pickleProtocol))
                fh.close()

                # Set persistance state to True
                self.persistenceState["moroutes"] = True

            if scope in ["all", "mtroutes"]:
                # Persist mtroutes configuration
                path = "%s/%s.router-mtroutes" % (self.config.store_path, profile)
                self.log.info("Persisting current MTRoutingTable to [%s] profile in %s" % (profile, path))

                fh = open(path, "w")
                # Write configuration with datetime stamp
                fh.write("Persisted on %s [Jasmin %s]\n" % (time.strftime("%c"), jasmin.get_release()))
                fh.write(pickle.dumps(self.mt_routing_table, self.pickleProtocol))
                fh.close()

                # Set persistance state to True
                self.persistenceState["mtroutes"] = True

        except IOError:
            self.log.error("Cannot persist to %s" % path)
            return False
        except Exception, e:
            self.log.error("Unknown error occurred while persisting configuration: %s" % e)
            return False
Exemple #15
0
    def test_auth_success(self):
        testPassword = '******' % random.randrange(100, 200)
        self.JCliConfigInstance.admin_password = md5(testPassword).digest()

        commands = [{'command': self.JCliConfigInstance.admin_username},
                    {'command': testPassword, 'expect': 'Welcome to Jasmin %s console' % jasmin.get_release(), 'noecho': True}]
        return self._test(r'jcli : ', commands)
    def test_version_release(self):
        yield self.connect('127.0.0.1', self.pbPort)

        version_release = yield self.version_release()

        self.assertEqual(version_release, jasmin.get_release())
Exemple #17
0
 def perspective_version_release(self):
     return jasmin.get_release()
Exemple #18
0
    def perspective_persist(self, profile='jcli-prod', scope='all'):
        try:
            if scope in ['all', 'groups']:
                # Persist groups configuration
                path = '%s/%s.router-groups' % (self.config.store_path, profile)
                self.log.info('Persisting current Groups configuration to [%s] profile in %s',
                              profile, path)

                fh = open(path, 'w')
                # Write configuration with datetime stamp
                fh.write('Persisted on %s [Jasmin %s]\n' % (time.strftime("%c"), jasmin.get_release()))
                fh.write(pickle.dumps(self.groups, self.pickleProtocol))
                fh.close()

                # Set persistance state to True
                self.persistenceState['groups'] = True

            if scope in ['all', 'users']:
                # Persist users configuration
                path = '%s/%s.router-users' % (self.config.store_path, profile)
                self.log.info('Persisting current Users configuration to [%s] profile in %s',
                              profile, path)

                fh = open(path, 'w')
                # Write configuration with datetime stamp
                fh.write('Persisted on %s [Jasmin %s]\n' % (time.strftime("%c"), jasmin.get_release()))
                fh.write(pickle.dumps(self.users, self.pickleProtocol))
                fh.close()

                # Set persistance state to True
                self.persistenceState['users'] = True
                for u in self.users:
                    u.mt_credential.quotas_updated = False

            if scope in ['all', 'moroutes']:
                # Persist moroutes configuration
                path = '%s/%s.router-moroutes' % (self.config.store_path, profile)
                self.log.info('Persisting current MORoutingTable to [%s] profile in %s', profile, path)

                fh = open(path, 'w')
                # Write configuration with datetime stamp
                fh.write('Persisted on %s [Jasmin %s]\n' % (time.strftime("%c"), jasmin.get_release()))
                fh.write(pickle.dumps(self.mo_routing_table, self.pickleProtocol))
                fh.close()

                # Set persistance state to True
                self.persistenceState['moroutes'] = True

            if scope in ['all', 'mtroutes']:
                # Persist mtroutes configuration
                path = '%s/%s.router-mtroutes' % (self.config.store_path, profile)
                self.log.info('Persisting current MTRoutingTable to [%s] profile in %s', profile, path)

                fh = open(path, 'w')
                # Write configuration with datetime stamp
                fh.write('Persisted on %s [Jasmin %s]\n' % (time.strftime("%c"), jasmin.get_release()))
                fh.write(pickle.dumps(self.mt_routing_table, self.pickleProtocol))
                fh.close()

                # Set persistance state to True
                self.persistenceState['mtroutes'] = True

            if scope in ['all', 'mointerceptors']:
                # Persist mointerceptors configuration
                path = '%s/%s.router-mointerceptors' % (self.config.store_path, profile)
                self.log.info('Persisting current MOInterceptionTable to [%s] profile in %s',
                              profile, path)

                fh = open(path, 'w')
                # Write configuration with datetime stamp
                fh.write('Persisted on %s [Jasmin %s]\n' % (time.strftime("%c"), jasmin.get_release()))
                fh.write(pickle.dumps(self.mo_interception_table, self.pickleProtocol))
                fh.close()

                # Set persistance state to True
                self.persistenceState['mointerceptors'] = True

            if scope in ['all', 'mtinterceptors']:
                # Persist mtinterceptors configuration
                path = '%s/%s.router-mtinterceptors' % (self.config.store_path, profile)
                self.log.info('Persisting current MTInterceptionTable to [%s] profile in %s',
                              profile, path)

                fh = open(path, 'w')
                # Write configuration with datetime stamp
                fh.write('Persisted on %s [Jasmin %s]\n' % (time.strftime("%c"), jasmin.get_release()))
                fh.write(pickle.dumps(self.mt_interception_table, self.pickleProtocol))
                fh.close()

                # Set persistance state to True
                self.persistenceState['mtinterceptors'] = True

        except IOError:
            self.log.error('Cannot persist to %s', path)
            return False
        except Exception as e:
            self.log.error('Unknown error occurred while persisting configuration: %s', e)
            return False

        return True
Exemple #19
0
 def perspective_version_release(self):
     return jasmin.get_release()
Exemple #20
0
 def render_GET(self, request):
     self.log.debug("Rendering / response with args: %s from %s",
                    request.args, request.getClientIP())
     request.setResponseCode(200)
     return jasmin.get_release().encode()
Exemple #21
0
    def perspective_persist(self, profile='jcli-prod', scope='all'):
        try:
            if scope in ['all', 'groups']:
                # Persist groups configuration
                path = '%s/%s.router-groups' % (self.config.store_path,
                                                profile)
                self.log.info(
                    'Persisting current Groups configuration to [%s] profile in %s'
                    % (profile, path))

                fh = open(path, 'w')
                # Write configuration with datetime stamp
                fh.write('Persisted on %s [Jasmin %s]\n' %
                         (time.strftime("%c"), jasmin.get_release()))
                fh.write(pickle.dumps(self.groups, self.pickleProtocol))
                fh.close()

                # Set persistance state to True
                self.persistenceState['groups'] = True

            if scope in ['all', 'users']:
                # Persist users configuration
                path = '%s/%s.router-users' % (self.config.store_path, profile)
                self.log.info(
                    'Persisting current Users configuration to [%s] profile in %s'
                    % (profile, path))

                fh = open(path, 'w')
                # Write configuration with datetime stamp
                fh.write('Persisted on %s [Jasmin %s]\n' %
                         (time.strftime("%c"), jasmin.get_release()))
                fh.write(pickle.dumps(self.users, self.pickleProtocol))
                fh.close()

                # Set persistance state to True
                self.persistenceState['users'] = True
                for u in self.users:
                    u.mt_credential.quotas_updated = False

            if scope in ['all', 'moroutes']:
                # Persist moroutes configuration
                path = '%s/%s.router-moroutes' % (self.config.store_path,
                                                  profile)
                self.log.info(
                    'Persisting current MORoutingTable to [%s] profile in %s' %
                    (profile, path))

                fh = open(path, 'w')
                # Write configuration with datetime stamp
                fh.write('Persisted on %s [Jasmin %s]\n' %
                         (time.strftime("%c"), jasmin.get_release()))
                fh.write(
                    pickle.dumps(self.mo_routing_table, self.pickleProtocol))
                fh.close()

                # Set persistance state to True
                self.persistenceState['moroutes'] = True

            if scope in ['all', 'mtroutes']:
                # Persist mtroutes configuration
                path = '%s/%s.router-mtroutes' % (self.config.store_path,
                                                  profile)
                self.log.info(
                    'Persisting current MTRoutingTable to [%s] profile in %s' %
                    (profile, path))

                fh = open(path, 'w')
                # Write configuration with datetime stamp
                fh.write('Persisted on %s [Jasmin %s]\n' %
                         (time.strftime("%c"), jasmin.get_release()))
                fh.write(
                    pickle.dumps(self.mt_routing_table, self.pickleProtocol))
                fh.close()

                # Set persistance state to True
                self.persistenceState['mtroutes'] = True

        except IOError:
            self.log.error('Cannot persist to %s' % path)
            return False
        except Exception, e:
            self.log.error(
                'Unknown error occurred while persisting configuration: %s' %
                e)
            return False
Exemple #22
0
class JCliProtocol(CmdProtocol):
    motd = 'Welcome to Jasmin %s console\nType help or ? to list commands.\n' % jasmin.get_release(
    )
    prompt = 'jcli : '

    def __init__(self, log_category='jcli'):
        CmdProtocol.__init__(self, log_category)

        # Init authentication
        self.authentication = {
            'username': None,
            'password': None,
            'printedPassword': None,
            'auth': False
        }

        # Provision commands
        if 'persist' not in self.commands:
            self.commands.append('persist')
        if 'load' not in self.commands:
            self.commands.append('load')
        if 'user' not in self.commands:
            self.commands.append('user')
        if 'group' not in self.commands:
            self.commands.append('group')
        if 'filter' not in self.commands:
            self.commands.append('filter')
        if 'mointerceptor' not in self.commands:
            self.commands.append('mointerceptor')
        if 'mtinterceptor' not in self.commands:
            self.commands.append('mtinterceptor')
        if 'morouter' not in self.commands:
            self.commands.append('morouter')
        if 'mtrouter' not in self.commands:
            self.commands.append('mtrouter')
        if 'smppccm' not in self.commands:
            self.commands.append('smppccm')
        if 'httpccm' not in self.commands:
            self.commands.append('httpccm')
        if 'stats' not in self.commands:
            self.commands.append('stats')

    def connectionMade(self):
        # Provision security
        if not self.factory.config.authentication:
            # Will not require an authentication from client
            self.authentication = {
                'username': '******',
                'password': None,
                'printedPassword': None,
                'auth': True
            }

        # Call CmdProtocol.connectionMade() depending on the security policy
        if self.authentication['auth']:
            CmdProtocol.connectionMade(self)
        elif self.authentication['username'] is None:
            self.oldPrompt = self.prompt
            self.prompt = 'Username: '******'Authentication required.\n\n')

        # Provision managers
        self.managers = {
            'user': UsersManager(self, self.factory.pb),
            'group': GroupsManager(self, self.factory.pb),
            'mointerceptor': MoInterceptorManager(self, self.factory.pb),
            'mtinterceptor': MtInterceptorManager(self, self.factory.pb),
            'morouter': MoRouterManager(self, self.factory.pb),
            'mtrouter': MtRouterManager(self, self.factory.pb),
            'smppccm': SmppCCManager(self, self.factory.pb),
            'filter': FiltersManager(self),
            'httpccm': HttpccManager(self),
            'stats': StatsManager(self, self.factory.pb)
        }

    def lineReceived(self, line):
        """Go to CmdProtocol.lineReceived when authenticated only"""

        if self.authentication['auth']:
            return CmdProtocol.lineReceived(self, line)
        elif self.authentication['username'] is None:
            return self.auth_username(line)
        elif self.authentication['password'] is None:
            return self.auth_password(line)

    def characterReceived(self, ch, moreCharactersComing):
        if self.mode == 'insert':
            self.lineBuffer.insert(self.lineBufferIndex, ch)
        else:
            self.lineBuffer[self.lineBufferIndex:self.lineBufferIndex +
                            1] = [ch]
        self.lineBufferIndex += 1

        # Dont print back chars if password is being entered
        if (not self.authentication['auth']
                and self.authentication['username'] is not None
                and self.authentication['password'] is None):
            return
        else:
            self.terminal.write(ch)

    def handle_TAB(self):
        """TABulation is only enabled when authenticated"""

        if self.authentication['auth']:
            return CmdProtocol.handle_TAB(self)

    def auth_username(self, username):
        """Save typed username and prompt for password"""

        username = username.strip()
        if username:
            self.authentication['username'] = username
            self.prompt = 'Password: '******'[sref:%s] Received AUTH Username: %s',
                           self.sessionRef, self.authentication['username'])

        return self.sendData()

    def auth_password(self, password):
        """Authentify Username & Password against configured (jasmin.cfg) credentials
        """

        self.authentication['password'] = password.strip()
        self.authentication['printedPassword'] = ''
        for _ in password:
            self.authentication['printedPassword'] += '*'
        self.log.debug('[sref:%s] Received AUTH Password: %s', self.sessionRef,
                       self.authentication['printedPassword'])

        # Authentication check against configured admin
        self.authentication['username'] = self.authentication[
            'username'].decode('ascii')
        if (self.authentication['username']
                == self.factory.config.admin_username
                and md5(self.authentication['password']).digest()
                == self.factory.config.admin_password):
            # Authenticated user
            self.authentication['auth'] = True
            self.prompt = self.oldPrompt
            self.drawMotd()
        else:
            self.prompt = 'Username: '******'username': None,
                'password': None,
                'printedPassword': None,
                'auth': False
            }
            return self.sendData('Incorrect Username/Password.\n')

        return self.sendData()

    @options([
        make_option(
            '-l',
            '--list',
            action="store_true",
            help="List all users or a group users when provided with GID"),
        make_option('-a', '--add', action="store_true", help="Add user"),
        make_option(
            '-e', '--enable', type="string", metavar="UID",
            help="Enable user"),
        make_option('-d',
                    '--disable',
                    type="string",
                    metavar="UID",
                    help="Disable user"),
        make_option('-u',
                    '--update',
                    type="string",
                    metavar="UID",
                    help="Update user using it's UID"),
        make_option('-r',
                    '--remove',
                    type="string",
                    metavar="UID",
                    help="Remove user using it's UID"),
        make_option('-s',
                    '--show',
                    type="string",
                    metavar="UID",
                    help="Show user using it's UID"),
        make_option('--smpp-unbind',
                    type="string",
                    metavar="UID",
                    help="Unbind user from smpp server using it's UID"),
        make_option('--smpp-ban',
                    type="string",
                    metavar="UID",
                    help="Unbind and ban user from smpp server using it's UID")
    ], '')
    def do_user(self, arg, opts):
        """User management"""

        if opts.list:
            self.managers['user'].list(arg, opts)
        elif opts.add:
            self.managers['user'].add(arg, opts)
        elif opts.enable:
            self.managers['user'].enable(arg, opts)
        elif opts.disable:
            self.managers['user'].disable(arg, opts)
        elif opts.update:
            self.managers['user'].update(arg, opts)
        elif opts.remove:
            self.managers['user'].remove(arg, opts)
        elif opts.show:
            self.managers['user'].show(arg, opts)
        elif opts.smpp_unbind:
            self.managers['user'].unbind(arg, opts)
        elif opts.smpp_ban:
            self.managers['user'].ban(arg, opts)
        else:
            return self.sendData('Missing required option')

    @options([
        make_option('-l', '--list', action="store_true", help="List groups"),
        make_option('-a', '--add', action="store_true", help="Add group"),
        make_option('-e',
                    '--enable',
                    type="string",
                    metavar="GID",
                    help="Enable group"),
        make_option('-d',
                    '--disable',
                    type="string",
                    metavar="GID",
                    help="Disable group"),
        make_option('-r',
                    '--remove',
                    type="string",
                    metavar="GID",
                    help="Remove group using it's GID")
    ], '')
    def do_group(self, arg, opts):
        """Group management"""

        if opts.list:
            self.managers['group'].list(arg, opts)
        elif opts.add:
            self.managers['group'].add(arg, opts)
        elif opts.enable:
            self.managers['group'].enable(arg, opts)
        elif opts.disable:
            self.managers['group'].disable(arg, opts)
        elif opts.remove:
            self.managers['group'].remove(arg, opts)
        else:
            return self.sendData('Missing required option')

    @options([
        make_option('-l', '--list', action="store_true", help="List filters"),
        make_option('-a', '--add', action="store_true", help="Add filter"),
        make_option('-r',
                    '--remove',
                    type="string",
                    metavar="FID",
                    help="Remove filter using it's FID"),
        make_option('-s',
                    '--show',
                    type="string",
                    metavar="FID",
                    help="Show filter using it's FID")
    ], '')
    def do_filter(self, arg, opts):
        """Filter management"""

        if opts.list:
            self.managers['filter'].list(arg, opts)
        elif opts.add:
            self.managers['filter'].add(arg, opts)
        elif opts.remove:
            self.managers['filter'].remove(arg, opts)
        elif opts.show:
            self.managers['filter'].show(arg, opts)
        else:
            return self.sendData('Missing required option')

    @options([
        make_option('-l',
                    '--list',
                    action="store_true",
                    help="List HTTP client connectors"),
        make_option('-a',
                    '--add',
                    action="store_true",
                    help="Add a new HTTP client connector"),
        make_option('-r',
                    '--remove',
                    type="string",
                    metavar="CID",
                    help="Remove HTTP client connector using it's CID"),
        make_option('-s',
                    '--show',
                    type="string",
                    metavar="CID",
                    help="Show HTTP client connector using it's CID")
    ], '')
    def do_httpccm(self, arg, opts=None):
        """HTTP client connector management"""

        if opts.list:
            self.managers['httpccm'].list(arg, opts)
        elif opts.add:
            self.managers['httpccm'].add(arg, opts)
        elif opts.remove:
            self.managers['httpccm'].remove(arg, opts)
        elif opts.show:
            self.managers['httpccm'].show(arg, opts)
        else:
            return self.sendData('Missing required option')

    @options([
        make_option(
            '-l', '--list', action="store_true", help="List MO interceptors"),
        make_option('-a',
                    '--add',
                    action="store_true",
                    help="Add a new MO interceptor"),
        make_option('-r',
                    '--remove',
                    type="string",
                    metavar="ORDER",
                    help="Remove MO interceptor using it's ORDER"),
        make_option('-s',
                    '--show',
                    type="string",
                    metavar="ORDER",
                    help="Show MO interceptor using it's ORDER"),
        make_option('-f',
                    '--flush',
                    action="store_true",
                    help="Flush MO interception table")
    ], '')
    def do_mointerceptor(self, arg, opts=None):
        """MO Interceptor management"""

        if opts.list:
            self.managers['mointerceptor'].list(arg, opts)
        elif opts.add:
            self.managers['mointerceptor'].add(arg, opts)
        elif opts.remove:
            self.managers['mointerceptor'].remove(arg, opts)
        elif opts.show:
            self.managers['mointerceptor'].show(arg, opts)
        elif opts.flush:
            self.managers['mointerceptor'].flush(arg, opts)
        else:
            return self.sendData('Missing required option')

    @options([
        make_option(
            '-l', '--list', action="store_true", help="List MT interceptors"),
        make_option('-a',
                    '--add',
                    action="store_true",
                    help="Add a new MT interceptor"),
        make_option('-r',
                    '--remove',
                    type="string",
                    metavar="ORDER",
                    help="Remove MT interceptor using it's ORDER"),
        make_option('-s',
                    '--show',
                    type="string",
                    metavar="ORDER",
                    help="Show MT interceptor using it's ORDER"),
        make_option('-f',
                    '--flush',
                    action="store_true",
                    help="Flush MT interception table")
    ], '')
    def do_mtinterceptor(self, arg, opts=None):
        """MT Interceptor management"""

        if opts.list:
            self.managers['mtinterceptor'].list(arg, opts)
        elif opts.add:
            self.managers['mtinterceptor'].add(arg, opts)
        elif opts.remove:
            self.managers['mtinterceptor'].remove(arg, opts)
        elif opts.show:
            self.managers['mtinterceptor'].show(arg, opts)
        elif opts.flush:
            self.managers['mtinterceptor'].flush(arg, opts)
        else:
            return self.sendData('Missing required option')

    @options([
        make_option('-l', '--list', action="store_true",
                    help="List MO routes"),
        make_option(
            '-a', '--add', action="store_true", help="Add a new MO route"),
        make_option('-r',
                    '--remove',
                    type="string",
                    metavar="ORDER",
                    help="Remove MO route using it's ORDER"),
        make_option('-s',
                    '--show',
                    type="string",
                    metavar="ORDER",
                    help="Show MO route using it's ORDER"),
        make_option('-f',
                    '--flush',
                    action="store_true",
                    help="Flush MO routing table")
    ], '')
    def do_morouter(self, arg, opts=None):
        """MO Router management"""

        if opts.list:
            self.managers['morouter'].list(arg, opts)
        elif opts.add:
            self.managers['morouter'].add(arg, opts)
        elif opts.remove:
            self.managers['morouter'].remove(arg, opts)
        elif opts.show:
            self.managers['morouter'].show(arg, opts)
        elif opts.flush:
            self.managers['morouter'].flush(arg, opts)
        else:
            return self.sendData('Missing required option')

    @options([
        make_option('-l', '--list', action="store_true",
                    help="List MT routes"),
        make_option(
            '-a', '--add', action="store_true", help="Add a new MT route"),
        make_option('-r',
                    '--remove',
                    type="string",
                    metavar="ORDER",
                    help="Remove MT route using it's ORDER"),
        make_option('-s',
                    '--show',
                    type="string",
                    metavar="ORDER",
                    help="Show MT route using it's ORDER"),
        make_option('-f',
                    '--flush',
                    action="store_true",
                    help="Flush MT routing table")
    ], '')
    def do_mtrouter(self, arg, opts=None):
        """MT Router management"""

        if opts.list:
            self.managers['mtrouter'].list(arg, opts)
        elif opts.add:
            self.managers['mtrouter'].add(arg, opts)
        elif opts.remove:
            self.managers['mtrouter'].remove(arg, opts)
        elif opts.show:
            self.managers['mtrouter'].show(arg, opts)
        elif opts.flush:
            self.managers['mtrouter'].flush(arg, opts)
        else:
            return self.sendData('Missing required option')

    @options([
        make_option(
            '-l', '--list', action="store_true", help="List SMPP connectors"),
        make_option(
            '-a', '--add', action="store_true", help="Add SMPP connector"),
        make_option('-u',
                    '--update',
                    type="string",
                    metavar="CID",
                    help="Update SMPP connector configuration using it's CID"),
        make_option('-r',
                    '--remove',
                    type="string",
                    metavar="CID",
                    help="Remove SMPP connector using it's CID"),
        make_option('-s',
                    '--show',
                    type="string",
                    metavar="CID",
                    help="Show SMPP connector using it's CID"),
        make_option('-1',
                    '--start',
                    type="string",
                    metavar="CID",
                    help="Start SMPP connector using it's CID"),
        make_option('-0',
                    '--stop',
                    type="string",
                    metavar="CID",
                    help="Start SMPP connector using it's CID")
    ], '')
    def do_smppccm(self, arg, opts):
        """SMPP connector management"""

        if opts.list:
            self.managers['smppccm'].list(arg, opts)
        elif opts.add:
            self.managers['smppccm'].add(arg, opts)
        elif opts.update:
            self.managers['smppccm'].update(arg, opts)
        elif opts.remove:
            self.managers['smppccm'].remove(arg, opts)
        elif opts.show:
            self.managers['smppccm'].show(arg, opts)
        elif opts.start:
            self.managers['smppccm'].start(arg, opts)
        elif opts.stop:
            self.managers['smppccm'].stop(arg, opts)
        else:
            return self.sendData('Missing required option')

    @options([
        make_option('-p',
                    '--profile',
                    type="string",
                    default="jcli-prod",
                    help="Configuration profile, default: jcli-prod")
    ], '')
    def do_persist(self, arg, opts):
        """Persist current configuration profile to disk in PROFILE"""

        for _, manager in self.managers.items():
            if manager is not None and isinstance(manager, PersistableManager):
                manager.persist(arg, opts)
        self.sendData()

    @options([
        make_option('-p',
                    '--profile',
                    type="string",
                    default="jcli-prod",
                    help="Configuration profile, default: jcli-prod")
    ], '')
    def do_load(self, arg, opts):
        """Load configuration PROFILE profile from disk"""

        for _, manager in self.managers.items():
            if manager is not None and isinstance(manager, PersistableManager):
                manager.load(arg, opts)
        self.sendData()

    @options([
        make_option(None,
                    '--user',
                    type="string",
                    metavar="UID",
                    help="Show user stats using it's UID"),
        make_option(
            None, '--users', action="store_true", help="Show all users stats"),
        make_option(None,
                    '--smppc',
                    type="string",
                    metavar="CID",
                    help="Show smpp connector stats using it's CID"),
        make_option(None,
                    '--smppcs',
                    action="store_true",
                    help="Show all smpp connectors stats"),
        make_option(
            None, '--httpapi', action="store_true",
            help="Show HTTP API stats"),
        make_option(None,
                    '--smppsapi',
                    action="store_true",
                    help="Show SMPP Server API stats")
    ], '')
    def do_stats(self, arg, opts=None):
        """Stats management"""

        if opts.user:
            self.managers['stats'].user(arg, opts)
        elif opts.users:
            self.managers['stats'].users(arg, opts)
        elif opts.smppc:
            self.managers['stats'].smppc(arg, opts)
        elif opts.smppcs:
            self.managers['stats'].smppcs(arg, opts)
        elif opts.httpapi:
            self.managers['stats'].httpapi(arg, opts)
        elif opts.smppsapi:
            self.managers['stats'].smppsapi(arg, opts)
        else:
            return self.sendData('Missing required option')