Exemple #1
0
def _create_trigger(operations, op):
	operations.execute(CreateTrigger(
		op.table,
		Trigger(op.when, op.action, op.name),
		module=op.module,
		migration=op.migration
	))
Exemple #2
0
class Host(Base):
    """
	Host object.
	"""
    __tablename__ = 'hosts_def'
    __table_args__ = (Comment('Hosts'),
                      Index('hosts_def_u_hostname',
                            'domainid',
                            'name',
                            unique=True), Index('hosts_def_i_hgid', 'hgid'),
                      Index('hosts_def_i_entityid',
                            'entityid'), Index('hosts_def_i_aliasid',
                                               'aliasid'),
                      Index('hosts_def_i_cby',
                            'cby'), Index('hosts_def_i_mby', 'mby'),
                      Trigger('before', 'insert', 't_hosts_def_bi'),
                      Trigger('before', 'update', 't_hosts_def_bu'),
                      Trigger('after', 'insert', 't_hosts_def_ai'),
                      Trigger('after', 'update', 't_hosts_def_au'),
                      Trigger('after', 'delete', 't_hosts_def_ad'), {
                          'mysql_engine': 'InnoDB',
                          'mysql_charset': 'utf8',
                          'info': {
                              'cap_menu':
                              'BASE_HOSTS',
                              'cap_read':
                              'HOSTS_LIST',
                              'cap_create':
                              'HOSTS_CREATE',
                              'cap_edit':
                              'HOSTS_EDIT',
                              'cap_delete':
                              'HOSTS_DELETE',
                              'menu_name':
                              _('Hosts'),
                              'show_in_menu':
                              'modules',
                              'menu_main':
                              True,
                              'default_sort': ({
                                  'property': 'name',
                                  'direction': 'ASC'
                              }, ),
                              'grid_view':
                              ('hostid',
                               MarkupColumn(name='name',
                                            header_string=_('Name'),
                                            template='{__str__}',
                                            column_flex=3,
                                            sortable=True), 'domain', 'group',
                               'entity'),
                              'grid_hidden': ('hostid', 'domain'),
                              'form_view':
                              ('name', 'domain', 'group', 'entity', 'original',
                               'aliastype', 'descr', 'ctime', 'cby', 'mtime',
                               'mby'),
                              'easy_search': ('name', ),
                              'detail_pane':
                              ('netprofile_core.views', 'dpane_simple'),
                              'create_wizard':
                              Wizard(Step('name',
                                          'domain',
                                          'entity',
                                          title=_('New host data')),
                                     Step('group',
                                          'original',
                                          'aliastype',
                                          'descr',
                                          title=_('New host details')),
                                     title=_('Add new host'))
                          }
                      })
    id = Column('hostid',
                UInt32(),
                Sequence('hosts_def_hostid_seq'),
                Comment('Host ID'),
                primary_key=True,
                nullable=False,
                info={'header_string': _('ID')})
    group_id = Column('hgid',
                      UInt32(),
                      ForeignKey('hosts_groups.hgid',
                                 name='hosts_def_fk_hgid',
                                 onupdate='CASCADE'),
                      Comment('Host group ID'),
                      nullable=False,
                      info={
                          'header_string': _('Group'),
                          'filter_type': 'nplist',
                          'column_flex': 1
                      })
    entity_id = Column('entityid',
                       UInt32(),
                       ForeignKey('entities_def.entityid',
                                  name='hosts_def_fk_entityid',
                                  onupdate='CASCADE',
                                  ondelete='CASCADE'),
                       Comment('Entity ID'),
                       nullable=False,
                       info={
                           'header_string': _('Entity'),
                           'filter_type': 'none',
                           'column_flex': 1
                       })
    domain_id = Column('domainid',
                       UInt32(),
                       ForeignKey('domains_def.domainid',
                                  name='hosts_def_fk_domainid',
                                  onupdate='CASCADE'),
                       Comment('Domain ID'),
                       nullable=False,
                       info={
                           'header_string': _('Domain'),
                           'filter_type': 'nplist',
                           'column_flex': 2
                       })
    name = Column(Unicode(255),
                  Comment('Host Name'),
                  nullable=False,
                  info={'header_string': _('Name')})
    original_id = Column('aliasid',
                         UInt32(),
                         ForeignKey('hosts_def.hostid',
                                    name='hosts_def_fk_aliasid',
                                    ondelete='CASCADE',
                                    onupdate='CASCADE'),
                         Comment('Aliased host ID'),
                         nullable=True,
                         default=None,
                         server_default=text('NULL'),
                         info={
                             'header_string': _('Aliased'),
                             'filter_type': 'nplist'
                         })
    alias_type = Column('aliastype',
                        HostAliasType.db_type(),
                        Comment('Host alias type'),
                        nullable=False,
                        default=HostAliasType.symbolic,
                        server_default=HostAliasType.symbolic,
                        info={'header_string': _('Alias Type')})
    creation_time = Column('ctime',
                           TIMESTAMP(),
                           Comment('Time of creation'),
                           nullable=True,
                           default=None,
                           server_default=FetchedValue(),
                           info={
                               'header_string': _('Created'),
                               'read_only': True
                           })
    modification_time = Column('mtime',
                               TIMESTAMP(),
                               Comment('Time of last modification'),
                               CurrentTimestampDefault(on_update=True),
                               nullable=False,
                               info={
                                   'header_string': _('Modified'),
                                   'read_only': True
                               })
    created_by_id = Column('cby',
                           UInt32(),
                           ForeignKey('users.uid',
                                      name='hosts_def_fk_cby',
                                      ondelete='SET NULL',
                                      onupdate='CASCADE'),
                           Comment('Created by'),
                           nullable=True,
                           default=None,
                           server_default=text('NULL'),
                           info={
                               'header_string': _('Created'),
                               'read_only': True
                           })
    modified_by_id = Column('mby',
                            UInt32(),
                            ForeignKey('users.uid',
                                       name='hosts_def_fk_mby',
                                       ondelete='SET NULL',
                                       onupdate='CASCADE'),
                            Comment('Last modified by'),
                            nullable=True,
                            default=None,
                            server_default=text('NULL'),
                            info={
                                'header_string': _('Modified'),
                                'read_only': True
                            })
    description = Column('descr',
                         UnicodeText(),
                         Comment('Host description'),
                         nullable=True,
                         default=None,
                         server_default=text('NULL'),
                         info={'header_string': _('Description')})

    group = relationship('HostGroup', innerjoin=True, backref='hosts')
    entity = relationship('Entity',
                          innerjoin=True,
                          backref=backref('hosts',
                                          cascade='all, delete-orphan',
                                          passive_deletes=True))
    domain = relationship('Domain', innerjoin=True, backref='hosts')
    original = relationship('Host',
                            backref=backref('aliases',
                                            cascade='all, delete-orphan',
                                            passive_deletes=True),
                            remote_side=[id])
    created_by = relationship('User',
                              foreign_keys=created_by_id,
                              backref=backref('created_hosts',
                                              passive_deletes=True))
    modified_by = relationship('User',
                               foreign_keys=modified_by_id,
                               backref=backref('modified_hosts',
                                               passive_deletes=True))
    services = relationship('Service',
                            backref=backref('host', innerjoin=True),
                            cascade='all, delete-orphan',
                            passive_deletes=True)

    @property
    def real(self):
        if not self.original:
            return self
        h = self
        while h.original:
            h = h.original
        return h

    def __str__(self):
        if self.domain:
            return '%s.%s' % (str(self.name), str(self.domain))
        return str(self.name)

    @classmethod
    def resolve(cls, name, domain_aliases=True):
        parts = name.strip('.').split('.')
        num_parts = len(parts)
        if num_parts == 1:
            # TODO: support specifying default domain
            raise ValueError('Hostname must be fully qualified')
        variants = list(('.'.join(parts[:i]), '.'.join(parts[i:]))
                        for i in range(1, num_parts))
        sess = DBSession()
        for host_part, domain_part in variants:
            domain = Domain.resolve(domain_part, domain_aliases=domain_aliases)
            if domain is None:
                continue
            try:
                return sess.query(Host).filter(Host.domain == domain,
                                               Host.name == host_part).one()
            except NoResultFound:
                pass
Exemple #3
0
class Network(Base):
    """
	Network object.
	"""
    __tablename__ = 'nets_def'
    __table_args__ = (
        Comment('Networks'), Index('nets_def_u_name', 'name', unique=True),
        Index('nets_def_u_ipaddr', 'ipaddr', unique=True),
        Index('nets_def_u_ip6addr', 'ip6addr',
              unique=True), Index('nets_def_i_domainid', 'domainid'),
        Index('nets_def_i_netgid',
              'netgid'), Index('nets_def_i_rtid',
                               'rtid'), Index('nets_def_i_mgmtdid', 'mgmtdid'),
        Trigger('after', 'insert',
                't_nets_def_ai'), Trigger('after', 'update', 't_nets_def_au'),
        Trigger('after', 'delete', 't_nets_def_ad'), {
            'mysql_engine': 'InnoDB',
            'mysql_charset': 'utf8',
            'info': {
                'cap_menu':
                'BASE_NETS',
                'cap_read':
                'NETS_LIST',
                'cap_create':
                'NETS_CREATE',
                'cap_edit':
                'NETS_EDIT',
                'cap_delete':
                'NETS_DELETE',
                'menu_name':
                _('Networks'),
                'show_in_menu':
                'modules',
                'menu_main':
                True,
                'default_sort': ({
                    'property': 'name',
                    'direction': 'ASC'
                }, ),
                'grid_view':
                ('netid', 'name', 'domain', 'group', 'ipaddr', 'ip6addr',
                 MarkupColumn(
                     name='state',
                     header_string=_('State'),
                     template=TemplateObject(
                         'netprofile_networks:templates/networks_icons.mak'),
                     column_width=40,
                     column_resizable=False)),
                'grid_hidden': ('netid', 'domain', 'group'),
                'form_view': ('name', 'domain', 'group', 'management_device',
                              'enabled', 'public', 'ipaddr', 'cidr', 'ip6addr',
                              'cidr6', 'vlanid', 'routing_table', 'gueststart',
                              'guestend', 'gueststart6', 'guestend6', 'descr'),
                'easy_search': ('name', ),
                'detail_pane': ('netprofile_core.views', 'dpane_simple'),
                'create_wizard':
                SimpleWizard(title=_('Add new network'))
            }
        })
    id = Column('netid',
                UInt32(),
                Sequence('nets_def_netid_seq'),
                Comment('Network ID'),
                primary_key=True,
                nullable=False,
                info={'header_string': _('ID')})
    name = Column(Unicode(255),
                  Comment('Network name'),
                  nullable=False,
                  info={
                      'header_string': _('Name'),
                      'column_flex': 1
                  })
    domain_id = Column('domainid',
                       UInt32(),
                       ForeignKey('domains_def.domainid',
                                  name='nets_def_fk_domainid',
                                  onupdate='CASCADE'),
                       Comment('Domain ID'),
                       nullable=False,
                       info={
                           'header_string': _('Domain'),
                           'filter_type': 'nplist',
                           'column_flex': 1
                       })
    group_id = Column('netgid',
                      UInt32(),
                      ForeignKey('nets_groups.netgid',
                                 name='nets_def_fk_netgid',
                                 ondelete='SET NULL',
                                 onupdate='CASCADE'),
                      Comment('Network group ID'),
                      nullable=True,
                      default=None,
                      server_default=text('NULL'),
                      info={
                          'header_string': _('Group'),
                          'filter_type': 'nplist',
                          'column_flex': 1
                      })
    management_device_id = Column('mgmtdid',
                                  UInt32(),
                                  ForeignKey('devices_network.did',
                                             name='nets_def_fk_mgmtdid',
                                             ondelete='SET NULL',
                                             onupdate='CASCADE'),
                                  Comment('Management device ID'),
                                  nullable=True,
                                  default=None,
                                  server_default=text('NULL'),
                                  info={
                                      'header_string': _('Management Device'),
                                      'filter_type': 'none'
                                  })
    enabled = Column(NPBoolean(),
                     Comment('Is network enabled?'),
                     nullable=False,
                     default=True,
                     server_default=npbool(True),
                     info={'header_string': _('Enabled')})
    public = Column(NPBoolean(),
                    Comment('Is network visible to outsiders?'),
                    nullable=False,
                    default=True,
                    server_default=npbool(True),
                    info={'header_string': _('Public')})
    ipv4_address = Column('ipaddr',
                          IPv4Address(),
                          Comment('Network IPv4 address'),
                          nullable=True,
                          default=None,
                          server_default=text('NULL'),
                          info={'header_string': _('IPv4 Address')})
    ipv6_address = Column('ip6addr',
                          IPv6Address(),
                          Comment('Network IPv6 address'),
                          nullable=True,
                          default=None,
                          server_default=text('NULL'),
                          info={'header_string': _('IPv6 Address')})
    ipv4_cidr = Column('cidr',
                       UInt8(),
                       Comment('Network CIDR number'),
                       nullable=False,
                       default=24,
                       server_default=text('24'),
                       info={'header_string': _('IPv4 Netmask')})
    ipv6_cidr = Column('cidr6',
                       UInt8(),
                       Comment('Network CIDRv6 number'),
                       nullable=False,
                       default=64,
                       server_default=text('64'),
                       info={'header_string': _('IPv6 Netmask')})
    vlan_id = Column('vlanid',
                     UInt16(),
                     Comment('Network VLAN ID'),
                     nullable=False,
                     default=0,
                     server_default=text('0'),
                     info={'header_string': _('VLAN')})
    routing_table_id = Column('rtid',
                              UInt32(),
                              ForeignKey('rt_def.rtid',
                                         name='nets_def_fk_rtid',
                                         ondelete='SET NULL',
                                         onupdate='CASCADE'),
                              Comment('Routing table ID'),
                              nullable=True,
                              default=None,
                              server_default=text('NULL'),
                              info={
                                  'header_string': _('Routing Table'),
                                  'filter_type': 'nplist'
                              })
    ipv4_guest_start = Column(
        'gueststart',
        UInt16(),
        Comment('Start of IPv4 guest allocation area'),
        nullable=True,
        default=None,
        server_default=text('NULL'),
        info={'header_string': _('Start of IPv4 Guest Allocation Area')})
    ipv4_guest_end = Column(
        'guestend',
        UInt16(),
        Comment('End of IPv4 guest allocation area'),
        nullable=True,
        default=None,
        server_default=text('NULL'),
        info={'header_string': _('End of IPv4 Guest Allocation Area')})
    ipv6_guest_start = Column(
        'gueststart6',
        IPv6Offset(),
        Comment('Start of IPv6 guest allocation area'),
        nullable=True,
        default=None,
        server_default=text('NULL'),
        info={'header_string': _('Start of IPv6 Guest Allocation Area')})
    ipv6_guest_end = Column(
        'guestend6',
        IPv6Offset(),
        Comment('End of IPv6 guest allocation area'),
        nullable=True,
        default=None,
        server_default=text('NULL'),
        info={'header_string': _('End of IPv6 Guest Allocation Area')})
    description = Column('descr',
                         UnicodeText(),
                         Comment('Network description'),
                         nullable=True,
                         default=None,
                         server_default=text('NULL'),
                         info={'header_string': _('Description')})

    domain = relationship('Domain', innerjoin=True, backref='networks')
    group = relationship('NetworkGroup',
                         backref=backref('networks', passive_deletes=True))
    management_device = relationship('NetworkDevice',
                                     backref=backref('networks',
                                                     passive_deletes=True))
    routing_table = relationship('RoutingTable',
                                 backref=backref('networks',
                                                 passive_deletes=True))
    services = relationship('NetworkService',
                            backref=backref('network', innerjoin=True),
                            cascade='all, delete-orphan',
                            passive_deletes=True)

    @property
    def ipv4_network(self):
        if self.ipv4_address:
            return ipaddr.IPv4Network(
                '%s/%s' % (str(self.ipv4_address), str(self.ipv4_cidr)))

    @property
    def ipv6_network(self):
        if self.ipv6_address:
            return ipaddr.IPv6Network(
                '%s/%s' % (str(self.ipv6_address), str(self.ipv6_cidr)))

    def __str__(self):
        return str(self.name)
Exemple #4
0
class PaidService(Base):
    """
	Paid service mapping object.
	"""
    __tablename__ = 'paid_def'
    __table_args__ = (Comment('Paid service mappings'),
                      Index('paid_def_i_entityid',
                            'entityid'), Index('paid_def_i_aeid', 'aeid'),
                      Index('paid_def_i_hostid',
                            'hostid'), Index('paid_def_i_stashid', 'stashid'),
                      Index('paid_def_i_paidid',
                            'paidid'), Index('paid_def_i_active', 'active'),
                      Index('paid_def_i_qpend', 'qpend'),
                      Trigger('before', 'insert', 't_paid_def_bi'),
                      Trigger('before', 'update', 't_paid_def_bu'),
                      Trigger('after', 'insert', 't_paid_def_ai'),
                      Trigger('after', 'update', 't_paid_def_au'),
                      Trigger('after', 'delete', 't_paid_def_ad'), {
                          'mysql_engine': 'InnoDB',
                          'mysql_charset': 'utf8',
                          'info': {
                              'cap_menu':
                              'BASE_PAIDSERVICES',
                              'cap_read':
                              'PAIDSERVICES_LIST',
                              'cap_create':
                              'PAIDSERVICES_CREATE',
                              'cap_edit':
                              'PAIDSERVICES_EDIT',
                              'cap_delete':
                              'PAIDSERVICES_DELETE',
                              'default_sort': ({
                                  'property': 'qpend',
                                  'direction': 'DESC'
                              }, ),
                              'grid_view': ('epid', 'entity', 'stash', 'type',
                                            'active', 'qpend'),
                              'grid_hidden': ('epid', ),
                              'form_view': (),
                              'detail_pane':
                              ('netprofile_core.views', 'dpane_simple')
                          }
                      })
    id = Column('epid',
                UInt32(),
                Sequence('paid_def_epid_seq'),
                Comment('Paid service mapping ID'),
                primary_key=True,
                nullable=False,
                info={'header_string': _('ID')})
    entity_id = Column('entityid',
                       UInt32(),
                       Comment('Entity ID'),
                       ForeignKey('entities_def.entityid',
                                  name='paid_def_fk_entityid',
                                  onupdate='CASCADE',
                                  ondelete='CASCADE'),
                       nullable=False,
                       info={
                           'header_string': _('Entity'),
                           'filter_type': 'none',
                           'column_flex': 2
                       })
    access_entity_id = Column('aeid',
                              UInt32(),
                              Comment('Access entity ID'),
                              ForeignKey('entities_access.entityid',
                                         name='paid_def_fk_aeid',
                                         onupdate='CASCADE',
                                         ondelete='CASCADE'),
                              nullable=True,
                              default=None,
                              server_default=text('NULL'),
                              info={
                                  'header_string': _('Access Entity'),
                                  'filter_type': 'none',
                                  'column_flex': 2
                              })
    host_id = Column('hostid',
                     UInt32(),
                     Comment('Host ID'),
                     ForeignKey('hosts_def.hostid',
                                name='paid_def_fk_hostid',
                                onupdate='CASCADE',
                                ondelete='CASCADE'),
                     nullable=True,
                     default=None,
                     server_default=text('NULL'),
                     info={
                         'header_string': _('Host'),
                         'filter_type': 'none',
                         'column_flex': 2
                     })
    stash_id = Column('stashid',
                      UInt32(),
                      ForeignKey('stashes_def.stashid',
                                 name='paid_def_fk_stashid',
                                 onupdate='CASCADE',
                                 ondelete='CASCADE'),
                      Comment('Used stash ID'),
                      nullable=False,
                      info={
                          'header_string': _('Stash'),
                          'column_flex': 3
                      })
    paid_id = Column('paidid',
                     UInt32(),
                     ForeignKey('paid_types.paidid',
                                name='paid_def_fk_paidid',
                                onupdate='CASCADE'),
                     Comment('Type ID'),
                     nullable=False,
                     info={
                         'header_string': _('Stash'),
                         'column_flex': 3
                     })
    active = Column(NPBoolean(),
                    Comment('Is service active'),
                    nullable=False,
                    default=True,
                    server_default=npbool(True),
                    info={'header_string': _('Active')})
    quota_period_end = Column('qpend',
                              TIMESTAMP(),
                              Comment('End of quota period'),
                              nullable=True,
                              default=None,
                              server_default=FetchedValue(),
                              info={'header_string': _('Ends')})
    description = Column('descr',
                         UnicodeText(),
                         Comment('Description'),
                         nullable=True,
                         default=None,
                         server_default=text('NULL'),
                         info={'header_string': _('Description')})

    type = relationship('PaidServiceType',
                        innerjoin=True,
                        lazy='joined',
                        backref='paid_services')
    entity = relationship('Entity',
                          foreign_keys=entity_id,
                          innerjoin=True,
                          backref=backref('paid_services',
                                          cascade='all, delete-orphan',
                                          passive_deletes=True))
    access_entity = relationship('AccessEntity',
                                 foreign_keys=access_entity_id,
                                 backref=backref('paid_services_access',
                                                 cascade='all, delete-orphan',
                                                 passive_deletes=True))
    host = relationship('Host',
                        backref=backref('paid_services',
                                        cascade='all, delete-orphan',
                                        passive_deletes=True))
    stash = relationship('Stash',
                         innerjoin=True,
                         backref=backref('paid_services',
                                         cascade='all, delete-orphan',
                                         passive_deletes=True))

    def __str__(self):
        return '%s: %s' % (str(self.stash), str(self.type))
Exemple #5
0
class StashIO(Base):
	"""
	Stash I/O operation object.
	"""
	__tablename__ = 'stashes_io_def'
	__table_args__ = (
		Comment('Stashes input/output operations'),
		Index('stashes_io_def_i_siotypeid', 'siotypeid'),
		Index('stashes_io_def_i_stashid', 'stashid'),
		Index('stashes_io_def_i_currid', 'currid'),
		Index('stashes_io_def_i_uid', 'uid'),
		Index('stashes_io_def_i_entityid', 'entityid'),
		Index('stashes_io_def_i_ts', 'ts'),
		Trigger('before', 'insert', 't_stashes_io_def_bi'),
		Trigger('after', 'insert', 't_stashes_io_def_ai'),
		{
			'mysql_engine'  : 'InnoDB',
			'mysql_charset' : 'utf8',
			'info'          : {
				'cap_menu'      : 'BASE_STASHES',
				'cap_read'      : 'STASHES_IO',
				'cap_create'    : 'STASHES_IO',
				'cap_edit'      : '__NOPRIV__',
				'cap_delete'    : '__NOPRIV__',
				'menu_name'     : _('Operations'),
				'show_in_menu'  : 'modules',
				'default_sort'  : ({ 'property': 'ts', 'direction': 'DESC' },),
				'grid_view'     : ('sioid', 'type', 'stash', 'entity', 'user', 'ts', 'currency', 'diff'),
				'grid_hidden'   : ('sioid', 'currency'),
				'form_view'     : ('type', 'stash', 'currency', 'entity', 'user', 'ts', 'diff', 'descr'),
				'extra_data'    : ('formatted_difference',),
				'detail_pane'   : ('netprofile_core.views', 'dpane_simple'),

				'create_wizard' : Wizard(
					Step(
						'stash', 'type', 'diff', 'descr',
						id='generic',
						on_submit=_wizcb_stashio_submit
					),
					title=_('Add new operation')
				)
			}
		}
	)
	id = Column(
		'sioid',
		UInt32(),
		Sequence('stashes_io_def_sioid_seq'),
		Comment('Stash I/O ID'),
		primary_key=True,
		nullable=False,
		info={
			'header_string' : _('ID')
		}
	)
	type_id = Column(
		'siotypeid',
		UInt32(),
		Comment('Stash I/O type ID'),
		ForeignKey('stashes_io_types.siotypeid', name='stashes_io_def_fk_siotypeid', ondelete='CASCADE', onupdate='CASCADE'),
		nullable=False,
		info={
			'header_string' : _('Type'),
			'filter_type'   : 'nplist',
			'editor_xtype'  : 'simplemodelselect',
			'editor_config' : {
				'extraParams' : { '__ffilter' : [{
					'property' : 'oper_visible',
					'operator' : 'eq',
					'value'    : True
				}]}
			},
			'column_flex'   : 2
		}
	)
	stash_id = Column(
		'stashid',
		UInt32(),
		Comment('Stash ID'),
		ForeignKey('stashes_def.stashid', name='stashes_io_def_fk_stashid', ondelete='CASCADE', onupdate='CASCADE'),
		nullable=False,
		info={
			'header_string' : _('Stash'),
			'filter_type'   : 'none',
			'column_flex'   : 2
		}
	)
	currency_id = Column(
		'currid',
		UInt32(),
		Comment('Currency ID'),
		ForeignKey('currencies_def.currid', name='stashes_io_def_fk_currid', onupdate='CASCADE'), # ondelete=RESTRICT
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Currency'),
			'editor_xtype'  : 'simplemodelselect',
			'editor_config' : {
				'extraParams' : { '__ffilter' : [{
					'property' : 'oper_visible',
					'operator' : 'eq',
					'value'    : True
				}]}
			},
			'filter_type'   : 'nplist'
		}
	)
	user_id = Column(
		'uid',
		UInt32(),
		Comment('User ID'),
		ForeignKey('users.uid', name='stashes_io_def_fk_uid', ondelete='SET NULL', onupdate='CASCADE'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Operator'),
			'filter_type'   : 'nplist'
		}
	)
	entity_id = Column(
		'entityid',
		UInt32(),
		Comment('Related entity ID'),
		ForeignKey('entities_def.entityid', name='stashes_io_def_fk_entityid', ondelete='SET NULL', onupdate='CASCADE'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Entity'),
			'filter_type'   : 'none',
			'column_flex'   : 1
		}
	)
	timestamp = Column(
		'ts',
		TIMESTAMP(),
		Comment('Time stamp of operation'),
		CurrentTimestampDefault(),
		nullable=False,
		info={
			'header_string' : _('Date'),
			'column_flex'   : 1
		}
	)
	difference = Column(
		'diff',
		Money(),
		Comment('Operation result'),
		nullable=False,
		info={
			'header_string' : _('Change'),
			'column_xtype'  : 'templatecolumn',
			'template'      : '{formatted_difference}'
		}
	)
	description = Column(
		'descr',
		UnicodeText(),
		Comment('Description'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Description')
		}
	)

	type = relationship(
		'StashIOType',
		innerjoin=True,
		lazy='joined',
		backref=backref(
			'ios',
			cascade='all, delete-orphan',
			passive_deletes=True
		)
	)
	stash = relationship(
		'Stash',
		innerjoin=True,
		backref=backref(
			'ios',
			cascade='all, delete-orphan',
			passive_deletes=True
		)
	)
	currency = relationship(
		'Currency',
		lazy='joined',
		backref=backref(
			'ios',
			passive_deletes='all'
		)
	)
	user = relationship(
		'User',
		backref=backref(
			'stash_ios',
			passive_deletes=True
		)
	)
	entity = relationship(
		'Entity',
		backref=backref(
			'stash_ios',
			passive_deletes=True
		)
	)

	def __str__(self):
		return '%s: %s' % (
			str(self.stash),
			str(self.type)
		)

	def formatted_difference(self, req):
		return money_format(req, self.difference, currency=self.currency)
Exemple #6
0
class Stash(Base):
	"""
	Stash object.
	"""
	__tablename__ = 'stashes_def'
	__table_args__ = (
		Comment('Stashes of money'),
		Index('stashes_def_i_entityid', 'entityid'),
		Index('stashes_def_i_currid', 'currid'),
		Trigger('before', 'insert', 't_stashes_def_bi'),
		Trigger('before', 'update', 't_stashes_def_bu'),
		{
			'mysql_engine'  : 'InnoDB',
			'mysql_charset' : 'utf8',
			'info'          : {
				'cap_menu'      : 'BASE_STASHES',
				'cap_read'      : 'STASHES_LIST',
				'cap_create'    : 'STASHES_CREATE',
				'cap_edit'      : 'STASHES_EDIT',
				'cap_delete'    : 'STASHES_DELETE',
				'menu_name'     : _('Stashes'),
				'menu_main'     : True,
				'show_in_menu'  : 'modules',
				'default_sort'  : ({ 'property': 'name', 'direction': 'ASC' },),
				'grid_view'     : ('stashid', 'entity', 'name', 'currency', 'amount', 'credit'),
				'grid_hidden'   : ('stashid', 'currency'),
				'form_view'     : ('entity', 'name', 'currency', 'amount', 'credit', 'alltime_min', 'alltime_max'),
				'easy_search'   : ('name',),
				'extra_data'    : ('formatted_amount', 'formatted_credit'),
				'detail_pane'   : ('netprofile_core.views', 'dpane_simple'),
				'create_wizard' : SimpleWizard(title=_('Add new stash'))
			}
		}
	)
	id = Column(
		'stashid',
		UInt32(),
		Sequence('stashes_def_stashid_seq'),
		Comment('Stash ID'),
		primary_key=True,
		nullable=False,
		info={
			'header_string' : _('ID')
		}
	)
	entity_id = Column(
		'entityid',
		UInt32(),
		Comment('Owner entity ID'),
		ForeignKey('entities_def.entityid', name='stashes_def_fk_entityid', onupdate='CASCADE', ondelete='CASCADE'),
		nullable=False,
		info={
			'header_string' : _('Entity'),
			'filter_type'   : 'none',
			'column_flex'   : 2
		}
	)
	currency_id = Column(
		'currid',
		UInt32(),
		Comment('Currency ID'),
		ForeignKey('currencies_def.currid', name='stashes_def_fk_currid', onupdate='CASCADE'), # ondelete=RESTRICT
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Currency'),
			'editor_xtype'  : 'simplemodelselect',
			'editor_config' : {
				'extraParams' : { '__ffilter' : [{
					'property' : 'oper_visible',
					'operator' : 'eq',
					'value'    : True
				}]}
			},
			'filter_type'   : 'nplist'
		}
	)
	name = Column(
		Unicode(255),
		Comment('Stash name'),
		nullable=False,
		info={
			'header_string' : _('Name'),
			'column_flex'   : 3
		}
	)
	amount = Column(
		Money(),
		Comment('Stash balance'),
		nullable=False,
		default=0,
		server_default=text('0'),
		info={
			'header_string' : _('Balance'),
			'column_flex'   : 1,
			'column_xtype'  : 'templatecolumn',
			'template'      : '{formatted_amount}'
		}
	)
	credit = Column(
		Money(),
		Comment('Stash credit'),
		nullable=False,
		default=0,
		server_default=text('0'),
		info={
			'header_string' : _('Credit'),
			'column_flex'   : 1,
			'column_xtype'  : 'templatecolumn',
			'template'      : '{formatted_credit}'
		}
	)
	alltime_max = Column(
		Money(),
		Comment('All-time maximum balance'),
		nullable=False,
		default=0,
		server_default=text('0'),
		info={
			'header_string' : _('Max. Balance'),
			'read_only'     : True
		}
	)
	alltime_min = Column(
		Money(),
		Comment('All-time minimum balance'),
		nullable=False,
		default=0,
		server_default=text('0'),
		info={
			'header_string' : _('Min. Balance'),
			'read_only'     : True
		}
	)

	entity = relationship(
		'Entity',
		innerjoin=True,
		backref=backref(
			'stashes',
			cascade='all, delete-orphan',
			passive_deletes=True
		)
	)
	currency = relationship(
		'Currency',
		lazy='joined',
		backref=backref(
			'stashes',
			passive_deletes='all'
		)
	)

	def __str__(self):
		return '%s: %s' % (
			self.entity.nick,
			str(self.name)
		)

	def formatted_amount(self, req):
		return money_format(req, self.amount, currency=self.currency)

	def formatted_credit(self, req):
		return money_format(req, self.credit, currency=self.currency)
Exemple #7
0
class FuturePayment(Base):
	"""
	Future payment object.
	"""
	__tablename__ = 'futures_def'
	__table_args__ = (
		Comment('Future payments'),
		Index('futures_def_i_futures', 'state', 'ptime'),
		Index('futures_def_i_entityid', 'entityid'),
		Index('futures_def_i_stashid', 'stashid'),
		Index('futures_def_i_cby', 'cby'),
		Index('futures_def_i_mby', 'mby'),
		Index('futures_def_i_pby', 'pby'),
		Trigger('before', 'insert', 't_futures_def_bi'),
		Trigger('before', 'update', 't_futures_def_bu'),
		Trigger('after', 'insert', 't_futures_def_ai'),
		Trigger('after', 'update', 't_futures_def_au'),
		Trigger('after', 'delete', 't_futures_def_ad'),
		{
			'mysql_engine'  : 'InnoDB',
			'mysql_charset' : 'utf8',
			'info'          : {
				'cap_menu'      : 'BASE_FUTURES',
				'cap_read'      : 'FUTURES_LIST',
				'cap_create'    : 'FUTURES_CREATE',
				'cap_edit'      : 'FUTURES_EDIT',
				'cap_delete'    : '__NOPRIV__',
				# TODO: APPROVE/CANCEL
				'menu_name'     : _('Promised Payments'),
				'default_sort'  : ({ 'property': 'ctime', 'direction': 'DESC' },),
				'grid_view'     : ('futureid', 'entity', 'stash', 'diff', 'state', 'ctime'),
				'grid_hidden'   : ('futureid',),
				'form_view'     : (
					'entity', 'stash', 'diff',
					'state', 'origin',
					'ctime', 'created_by',
					'mtime', 'modified_by',
					'ptime', 'paid_by'
				),
				'detail_pane'   : ('netprofile_core.views', 'dpane_simple'),
				'create_wizard' : Wizard(
					Step(
						'entity', 'stash', 'diff', 'descr',
						id='generic',
						on_submit=_wizcb_future_submit
					),
					title=_('Add new promised payment')
				)
			}
		}
	)
	id = Column(
		'futureid',
		UInt32(),
		Sequence('futures_def_futureid_seq'),
		Comment('Future payment ID'),
		primary_key=True,
		nullable=False,
		info={
			'header_string': _('ID')
		}
	)
	entity_id = Column(
		'entityid',
		UInt32(),
		Comment('Entity ID'),
		ForeignKey('entities_def.entityid', name='futures_def_fk_entityid', onupdate='CASCADE', ondelete='SET NULL'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Entity'),
			'filter_type'   : 'none',
			'column_flex'   : 2
		}
	)
	stash_id = Column(
		'stashid',
		UInt32(),
		Comment('Stash ID'),
		ForeignKey('stashes_def.stashid', name='futures_def_fk_stashid', ondelete='CASCADE', onupdate='CASCADE'),
		nullable=False,
		info={
			'header_string' : _('Stash'),
			'filter_type'   : 'none',
			'column_flex'   : 2
		}
	)
	difference = Column(
		'diff',
		Money(),
		Comment('Payment result'),
		nullable=False,
		default=0.0,
		server_default=text('0.0'),
		info={
			'header_string' : _('Change')
		}
	)
	state = Column(
		FuturePaymentState.db_type(),
		Comment('Active / Paid / Cancelled'),
		nullable=False,
		default=FuturePaymentState.active,
		server_default=FuturePaymentState.active,
		info={
			'header_string' : _('State')
		}
	)
	origin = Column(
		FuturePaymentOrigin.db_type(),
		Comment('Origin of payment'),
		nullable=False,
		default=FuturePaymentOrigin.operator,
		server_default=FuturePaymentOrigin.operator,
		info={
			'header_string' : _('Origin')
		}
	)
	creation_time = Column(
		'ctime',
		TIMESTAMP(),
		Comment('Creation timestamp'),
		nullable=True,
		default=None,
		server_default=FetchedValue(),
		info={
			'header_string' : _('Created'),
			'read_only'     : True
		}
	)
	modification_time = Column(
		'mtime',
		TIMESTAMP(),
		Comment('Last modification timestamp'),
		CurrentTimestampDefault(on_update=True),
		nullable=False,
		info={
			'header_string' : _('Modified'),
			'read_only'     : True
		}
	)
	payment_time = Column(
		'ptime',
		TIMESTAMP(),
		Comment('Payment timestamp'),
		nullable=True,
		default=None,
		server_default=FetchedValue(),
		info={
			'header_string' : _('Confirmed'),
			'read_only'     : True
		}
	)
	created_by_id = Column(
		'cby',
		UInt32(),
		ForeignKey('users.uid', name='futures_def_fk_cby', ondelete='SET NULL', onupdate='CASCADE'),
		Comment('Created by'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Created'),
			'read_only'     : True
		}
	)
	modified_by_id = Column(
		'mby',
		UInt32(),
		ForeignKey('users.uid', name='futures_def_fk_mby', ondelete='SET NULL', onupdate='CASCADE'),
		Comment('Modified by'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Modified'),
			'read_only'     : True
		}
	)
	paid_by_id = Column(
		'pby',
		UInt32(),
		ForeignKey('users.uid', name='futures_def_fk_pby', ondelete='SET NULL', onupdate='CASCADE'),
		Comment('Payment confirmed by'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Confirmed'),
			'read_only'     : True
		}
	)
	description = Column(
		'descr',
		UnicodeText(),
		Comment('Description'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Description')
		}
	)

	stash = relationship(
		'Stash',
		innerjoin=True,
		backref=backref(
			'futures',
			cascade='all, delete-orphan',
			passive_deletes=True
		)
	)
	entity = relationship(
		'Entity',
		backref=backref(
			'stash_futures',
			passive_deletes=True
		)
	)
	created_by = relationship(
		'User',
		foreign_keys=created_by_id,
		backref=backref(
			'created_futures',
			passive_deletes=True
		)
	)
	modified_by = relationship(
		'User',
		foreign_keys=modified_by_id,
		backref=backref(
			'modified_futures',
			passive_deletes=True
		)
	)
	paid_by = relationship(
		'User',
		foreign_keys=paid_by_id,
		backref=backref(
			'paid_futures',
			passive_deletes=True
		)
	)

	def __str__(self):
		return '%s: %s' % (
			str(self.stash),
			str(self.difference)
		)
Exemple #8
0
class DomainTXTRecord(Base):
	"""
	Domain TXT record object.
	"""
	__tablename__ = 'domains_txtrr'
	__table_args__ = (
		Comment('Domain TXT records'),
		Index('domains_txtrr_u_txtrr', 'domainid', 'name', unique=True),
		Trigger('before', 'insert', 't_domains_txtrr_bi'),
		Trigger('before', 'update', 't_domains_txtrr_bu'),
		{
			'mysql_engine'  : 'InnoDB',
			'mysql_charset' : 'utf8',
			'info'          : {
				'cap_menu'      : 'BASE_DOMAINS',
				'cap_read'      : 'DOMAINS_LIST',
				'cap_create'    : 'DOMAINS_EDIT',
				'cap_edit'      : 'DOMAINS_EDIT',
				'cap_delete'    : 'DOMAINS_EDIT',
				'menu_name'     : _('TXT Records'),
				'default_sort'  : ({ 'property': 'name' ,'direction': 'ASC' },),
				'grid_view'     : ('txtrrid', 'name', 'domain', 'value'),
				'grid_hidden'   : ('txtrrid',),
				'form_view'		: ('name', 'domain', 'ttl', 'vis', 'value'),
				'easy_search'   : ('name', 'value'),
				'detail_pane'   : ('netprofile_core.views', 'dpane_simple'),

				'create_wizard' : SimpleWizard(title=_('Add new TXT record'))
			}
		}
	)
	id = Column(
		'txtrrid',
		UInt32(),
		Sequence('domains_txtrr_txtrrid_seq'),
		Comment('Text record ID'),
		primary_key=True,
		nullable=False,
		info={
			'header_string' : _('ID')
		}
	)
	domain_id = Column(
		'domainid',
		UInt32(),
		ForeignKey('domains_def.domainid', name='domains_txtrr_fk_domainid', ondelete='CASCADE', onupdate='CASCADE'),
		Comment('Domain ID'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Domain'),
			'column_flex'   : 1
		}
	)
	name = Column(
		ASCIIString(255),
		Comment('Text record name'),
		nullable=False,
		info={
			'header_string' : _('Name'),
			'column_flex'   : 1
		}
	)
	ttl = Column(
		UInt32(),
		Comment('Time to live'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('TTL')
		}
	)
	visibility = Column(
		'vis',
		ObjectVisibility.db_type(),
		Comment('Text record visibility'),
		nullable=False,
		default=ObjectVisibility.both,
		server_default=ObjectVisibility.both,
		info={
			'header_string' : _('Visibility')
		}
	)
	value = Column(
		ASCIITinyText(),
		Comment('Text record value'),
		nullable=False,
		info={
			'header_string' : _('Value'),
			'column_flex'   : 1
		}
	)

	domain = relationship(
		'Domain',
		innerjoin=True,
		backref='txt_records'
	)

	def __str__(self):
		if self.domain:
			return '%s.%s' % (
				str(self.name),
				str(self.domain)
			)
		return str(self.name)
Exemple #9
0
class Domain(Base):
	"""
	Domain object.
	"""
	__tablename__ = 'domains_def'
	__table_args__ = (
		Comment('Domains'),
		Index('domains_def_u_domain', 'parentid', 'name', unique=True),
		Trigger('after', 'insert', 't_domains_def_ai'),
		Trigger('after', 'update', 't_domains_def_au'),
		Trigger('after', 'delete', 't_domains_def_ad'),
		{
			'mysql_engine'  : 'InnoDB',
			'mysql_charset' : 'utf8',
			'info'          : {
				'cap_menu'      : 'BASE_DOMAINS',
				'cap_read'      : 'DOMAINS_LIST',
				'cap_create'    : 'DOMAINS_CREATE',
				'cap_edit'      : 'DOMAINS_EDIT',
				'cap_delete'    : 'DOMAINS_DELETE',

				'show_in_menu'  : 'modules',
				'menu_name'     : _('Domains'),
				'menu_main'     : True,
				'default_sort'  : ({ 'property': 'name' ,'direction': 'ASC' },),
				'grid_view'     : (
					'domainid',
					MarkupColumn(
						name='name',
						header_string=_('Name'),
						template='{__str__}',
						column_flex=1,
						sortable=True
					),
					'parent',
					MarkupColumn(
						name='state',
						header_string=_('State'),
						template=TemplateObject('netprofile_domains:templates/domain_icons.mak'),
						cell_class='np-nopad',
						column_width=60,
						column_resizable=False
					)
				),
				'grid_hidden'   : ('domainid',),
				'form_view'		: (
					'name', 'parent',
					'enabled', 'public', 'signed',
					'soa_refresh', 'soa_retry', 'soa_expire', 'soa_minimum',
					'spf_gen', 'spf_rule', 'spf_errmsg',
					'dkim_name', 'dkim_data', 'dkim_test', 'dkim_subdomains', 'dkim_strict',
					'dmarc_trailer',
					'descr'
				),
				'easy_search'   : ('name', 'descr'),
				'detail_pane'   : ('netprofile_core.views', 'dpane_simple'),

				'create_wizard' : Wizard(
					Step('name', 'parent', 'enabled', 'public', 'signed', 'descr', title=_('Domain info')),
					Step('soa_refresh', 'soa_retry', 'soa_expire', 'soa_minimum', 'dkim_name', 'dkim_data', title=_('DNS options')),
					title=_('Add new domain')
				)
			}
		}
	)
	id = Column(
		'domainid',
		UInt32(),
		Sequence('domains_def_domainid_seq'),
		Comment('Domain ID'),
		primary_key=True,
		nullable=False,
		info={
			'header_string' : _('ID')
		}
	)
	parent_id = Column(
		'parentid',
		UInt32(),
		ForeignKey('domains_def.domainid', name='domains_def_fk_parentid', onupdate='CASCADE'),
		Comment('Parent domain ID'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Parent'),
			'column_flex'   : 1
		}
	)
	name = Column(
		Unicode(255),
		Comment('Domain name'),
		nullable=False,
		info={
			'header_string' : _('Name')
		}
	)
	enabled = Column(
		NPBoolean(),
		Comment('Is domain enabled?'),
		nullable=False,
		default=True,
		server_default=npbool(True),
		info={
			'header_string' : _('Enabled')
		}
	)
	public = Column(
		NPBoolean(),
		Comment('Is domain visible to outsiders?'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Public')
		}
	)
	signed = Column(
		NPBoolean(),
		Comment('Needs DNSSEC signing?'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Signed')
		}
	)
	soa_refresh = Column(
		UInt32(),
		Comment('SOA refresh field'),
		nullable=False,
		default=3600,
		info={
			'header_string' : _('SOA Refresh')
		}
	)
	soa_retry = Column(
		UInt32(),
		Comment('SOA retry field'),
		nullable=False,
		default=300,
		info={
			'header_string' : _('SOA Retry')
		}
	)
	soa_expire = Column(
		UInt32(),
		Comment('SOA expire field'),
		nullable=False,
		default=1814400,
		info={
			'header_string' : _('SOA Expire')
		}
	)
	soa_minimum = Column(
		UInt32(),
		Comment('SOA minimum field'),
		nullable=False,
		default=3600,
		info={
			'header_string' : _('SOA Minimum')
		}
	)
	serial_date = Column(
		Date(),
		Comment('Domain serial date'),
		nullable=False,
		info={
			'header_string' : _('Serial Date'),
			'secret_value'  : True
		}
	)
	serial_revision = Column(
		'serial_rev',
		UInt8(),
		Comment('Domain serial revision'),
		nullable=False,
		default=1,
		info={
			'header_string' : _('Serial Revision'),
			'secret_value'  : True
		}
	)
	dkim_name = Column(
		ASCIIString(255),
		Comment('DKIM public key name'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('DKIM Name')
		}
	)
	dkim_data = Column(
		ASCIIText(),
		Comment('DKIM public key body'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('DKIM Key')
		}
	)
	dkim_test = Column(
		NPBoolean(),
		Comment('Use DKIM in test mode'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('DKIM Test')
		}
	)
	dkim_subdomains = Column(
		NPBoolean(),
		Comment('Propagate DKIM rules to subdomains'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('DKIM in Subdomains')
		}
	)
	dkim_strict = Column(
		NPBoolean(),
		Comment('Use DKIM strict check and discard'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('DKIM Strict')
		}
	)
	spf_generate = Column(
		'spf_gen',
		NPBoolean(),
		Comment('Generate SPF record'),
		nullable=False,
		default=True,
		server_default=npbool(True),
		info={
			'header_string' : _('Use SPF')
		}
	)
	spf_rule = Column(
		ASCIIText(),
		Comment('Custom SPF rule'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Custom SPF Rule')
		}
	)
	spf_error_message = Column(
		'spf_errmsg',
		UnicodeText(),
		Comment('Custom SPF error explanation string'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('SPF Error')
		}
	)
	dmarc_trailer = Column(
		ASCIIString(255),
		Comment('DMARC record trailer'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('DMARC Trailer')
		}
	)
	description = Column(
		'descr',
		UnicodeText(),
		Comment('Domain description'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Description')
		}
	)

	children = relationship(
		'Domain',
		backref=backref('parent', remote_side=[id])
	)

	@property
	def serial(self):
		if not self.serial_date:
			return str(self.serial_revision % 100)
		return '%s%02d' % (
			self.serial_date.strftime('%Y%m%d'),
			(self.serial_revision % 100)
		)

	def __str__(self):
		if self.parent:
			return '%s.%s' % (
				str(self.name),
				str(self.parent)
			)
		return str(self.name)

	@classmethod
	def resolve(cls, name, domain_aliases=True):
		name = name.strip('.')
		sess = DBSession()
		candidates = [(None, domain_candidates(name), None)]

		while len(candidates) > 0:
			old_candidates = candidates
			candidates = []
			domain_cond = []
			da_cond = []
			for domain, names, suffix in old_candidates:
				if domain is None or isinstance(domain, Domain):
					domain_cond.append(and_(
						Domain.parent_id == (domain.id if domain else None),
						Domain.name.in_(names)
					))
				if not domain_aliases:
					continue
				if domain is None or isinstance(domain, DomainAlias):
					da_cond.append(and_(
						DomainAlias.parent_id == (domain.id if domain else None),
						DomainAlias.name.in_(names)
					))
			if len(domain_cond) > 0:
				for domain in sess.query(Domain).filter(or_(*domain_cond)):
					if suffix is None:
						domain_name = str(domain)
					else:
						domain_name = '.'.join((domain.name, suffix))
					if name == domain_name:
						return domain
					offset = name.find('.' + domain_name)
					if offset > 0:
						left_part = name[:offset]
						candidates.append((domain, domain_candidates(left_part), domain_name))
			if domain_aliases and len(da_cond) > 0:
				for da in sess.query(DomainAlias).filter(or_(*da_cond)):
					if suffix is None:
						domain_name = str(da)
					else:
						domain_name = '.'.join((da.name, suffix))
					if name == domain_name:
						return da.domain
					offset = name.find('.' + domain_name)
					if offset > 0:
						left_part = name[:offset]
						dc = domain_candidates(left_part)
						candidates.extend((
							(da, dc, domain_name),
							(da.domain, dc, domain_name)
						))
Exemple #10
0
class AccessSession(Base):
    """
	Session definition
	"""
    __tablename__ = 'sessions_def'
    __table_args__ = (Comment('Access sessions'),
                      Index('sessions_def_u_session',
                            'stationid',
                            'name',
                            unique=True),
                      Index('sessions_def_i_entityid', 'entityid'),
                      Index('sessions_def_i_updatets', 'updatets'),
                      Index('sessions_def_i_destid', 'destid'),
                      Index('sessions_def_i_ipaddrid', 'ipaddrid'),
                      Index('sessions_def_i_ip6addrid',
                            'ip6addrid'), Index('sessions_def_i_nasid',
                                                'nasid'),
                      Trigger('before', 'delete', 't_sessions_def_bd'),
                      Trigger('after', 'delete', 't_sessions_def_ad'), {
                          'mysql_engine': 'InnoDB',
                          'mysql_charset': 'utf8',
                          'info': {
                              'cap_menu':
                              'BASE_SESSIONS',
                              'cap_read':
                              'SESSIONS_LIST',
                              'cap_create':
                              '__NOPRIV__',
                              'cap_edit':
                              '__NOPRIV__',
                              'cap_delete':
                              'SESSIONS_DISCONNECT',
                              'menu_name':
                              _('Sessions'),
                              'show_in_menu':
                              'modules',
                              'menu_main':
                              True,
                              'default_sort': ({
                                  'property': 'updatets',
                                  'direction': 'DESC'
                              }, ),
                              'grid_view':
                              ('sessid', 'nas', 'name', 'entity', 'csid',
                               'called', 'ut_ingress', 'ut_egress', 'startts',
                               'updatets'),
                              'grid_hidden': ('sessid', 'name', 'called'),
                              'form_view':
                              ('stationid', 'nas', 'called', 'name', 'entity',
                               'csid', 'ipv4_address', 'ipv6_address',
                               'ut_ingress', 'ut_egress', 'destination',
                               'startts', 'updatets', 'pol_ingress',
                               'pol_egress'),
                              'easy_search': ('name', 'csid'),
                              'detail_pane':
                              ('netprofile_core.views', 'dpane_simple')
                          }
                      })
    id = Column('sessid',
                UInt64(),
                Sequence('sessions_def_sessid_seq'),
                Comment('Session ID'),
                primary_key=True,
                nullable=False,
                info={'header_string': _('ID')})
    name = Column(ASCIIString(255),
                  Comment('Session name'),
                  nullable=False,
                  info={
                      'header_string': _('Name'),
                      'column_flex': 2
                  })
    station_id = Column(
        'stationid',
        UInt32(),
        Comment('Station ID'),
        # TODO: add foreign key to hosts?
        nullable=False,
        default=1,
        server_default=text('1'),
        info={'header_string': _('Station')})
    entity_id = Column('entityid',
                       UInt32(),
                       Comment('Access entity ID'),
                       ForeignKey('entities_access.entityid',
                                  name='sessions_def_fk_entityid',
                                  ondelete='SET NULL',
                                  onupdate='CASCADE'),
                       nullable=True,
                       default=None,
                       server_default=text('NULL'),
                       info={
                           'header_string': _('Entity'),
                           'filter_type': 'none',
                           'column_flex': 1
                       })
    ipv4_address_id = Column('ipaddrid',
                             UInt32(),
                             Comment('IPv4 address ID'),
                             ForeignKey('ipaddr_def.ipaddrid',
                                        name='sessions_def_fk_ipaddrid',
                                        ondelete='SET NULL',
                                        onupdate='CASCADE'),
                             nullable=True,
                             default=None,
                             server_default=text('NULL'),
                             info={
                                 'header_string': _('IPv4 Address'),
                                 'filter_type': 'none'
                             })
    ipv6_address_id = Column('ip6addrid',
                             UInt64(),
                             Comment('IPv6 address ID'),
                             ForeignKey('ip6addr_def.ip6addrid',
                                        name='sessions_def_fk_ip6addrid',
                                        ondelete='SET NULL',
                                        onupdate='CASCADE'),
                             nullable=True,
                             default=None,
                             server_default=text('NULL'),
                             info={
                                 'header_string': _('IPv6 Address'),
                                 'filter_type': 'none'
                             })
    destination_id = Column('destid',
                            UInt32(),
                            Comment('Accounting destination ID'),
                            ForeignKey('dest_def.destid',
                                       name='sessions_def_fk_destid',
                                       ondelete='SET NULL',
                                       onupdate='CASCADE'),
                            nullable=True,
                            default=None,
                            server_default=text('NULL'),
                            info={
                                'header_string': _('Destination'),
                                'filter_type': 'none'
                            })
    nas_id = Column('nasid',
                    UInt32(),
                    Comment('Network access server ID'),
                    ForeignKey('nas_def.nasid',
                               name='sessions_def_fk_nasid',
                               ondelete='SET NULL',
                               onupdate='CASCADE'),
                    nullable=True,
                    default=None,
                    server_default=text('NULL'),
                    info={
                        'header_string': _('NAS'),
                        'filter_type': 'nplist',
                        'column_flex': 1
                    })
    calling_station_id = Column('csid',
                                ASCIIString(255),
                                Comment('Calling station ID'),
                                nullable=True,
                                default=None,
                                server_default=text('NULL'),
                                info={
                                    'header_string': _('Calling Station'),
                                    'column_flex': 1
                                })
    called_station_id = Column('called',
                               ASCIIString(255),
                               Comment('Called station ID'),
                               nullable=True,
                               default=None,
                               server_default=text('NULL'),
                               info={
                                   'header_string': _('Called Station'),
                                   'column_flex': 1
                               })
    start_timestamp = Column('startts',
                             TIMESTAMP(),
                             Comment('Session start time'),
                             nullable=True,
                             default=None,
                             info={'header_string': _('Started')})
    update_timestamp = Column('updatets',
                              TIMESTAMP(),
                              Comment('Accounting update time'),
                              nullable=True,
                              default=None,
                              info={'header_string': _('Updated')})
    used_ingress_traffic = Column('ut_ingress',
                                  Traffic(),
                                  Comment('Used ingress traffic'),
                                  nullable=False,
                                  default=0,
                                  server_default=text('0'),
                                  info={'header_string': _('Used Ingress')})
    used_egress_traffic = Column('ut_egress',
                                 Traffic(),
                                 Comment('Used egress traffic'),
                                 nullable=False,
                                 default=0,
                                 server_default=text('0'),
                                 info={'header_string': _('Used Egress')})
    ingress_policy = Column('pol_ingress',
                            ASCIIString(255),
                            Comment('Ingress traffic policy'),
                            nullable=True,
                            default=None,
                            server_default=text('NULL'),
                            info={'header_string': _('Ingress Policy')})
    egress_policy = Column('pol_egress',
                           ASCIIString(255),
                           Comment('Egress traffic policy'),
                           nullable=True,
                           default=None,
                           server_default=text('NULL'),
                           info={'header_string': _('Egress Policy')})

    entity = relationship('AccessEntity',
                          backref=backref('sessions', passive_deletes=True))
    ipv4_address = relationship('IPv4Address',
                                backref=backref('sessions',
                                                passive_deletes=True))
    ipv6_address = relationship('IPv6Address',
                                backref=backref('sessions',
                                                passive_deletes=True))
    destination = relationship('Destination',
                               backref=backref('sessions',
                                               passive_deletes=True))
    nas = relationship('NAS',
                       backref=backref('sessions', passive_deletes=True))

    def __str__(self):
        return '%s' % str(self.name)
Exemple #11
0
def _drop_trigger(operations, op):
	operations.execute(DropTrigger(
		op.table,
		Trigger(op.when, op.action, op.name),
		module=op.module
	))
Exemple #12
0
class IPv4Address(Base):
    """
	IPv4 address object.
	"""
    __tablename__ = 'ipaddr_def'
    __table_args__ = (Comment('IPv4 addresses'),
                      Index('ipaddr_def_u_address',
                            'netid',
                            'offset',
                            unique=True), Index('ipaddr_def_i_hostid',
                                                'hostid'),
                      Index('ipaddr_def_i_poolid',
                            'poolid'), Index('ipaddr_def_i_inuse', 'inuse'),
                      Trigger('before', 'insert', 't_ipaddr_def_bi'),
                      Trigger('before', 'update', 't_ipaddr_def_bu'),
                      Trigger('after', 'insert', 't_ipaddr_def_ai'),
                      Trigger('after', 'update', 't_ipaddr_def_au'),
                      Trigger('after', 'delete', 't_ipaddr_def_ad'), {
                          'mysql_engine': 'InnoDB',
                          'mysql_charset': 'utf8',
                          'info': {
                              'cap_menu':
                              'BASE_IPADDR',
                              'cap_read':
                              'IPADDR_LIST',
                              'cap_create':
                              'IPADDR_CREATE',
                              'cap_edit':
                              'IPADDR_EDIT',
                              'cap_delete':
                              'IPADDR_DELETE',
                              'menu_name':
                              _('IPv4 Addresses'),
                              'show_in_menu':
                              'modules',
                              'grid_view':
                              ('ipaddrid', 'host',
                               MarkupColumn(name='offset',
                                            header_string=_('Address'),
                                            template='{__str__}',
                                            column_flex=1,
                                            sortable=True), 'hwaddr', 'vis',
                               'owned', 'inuse'),
                              'grid_hidden': ('ipaddrid', ),
                              'form_view':
                              ('host', 'network', 'offset', 'hwaddr', 'ttl',
                               'pool', 'vis', 'owned', 'inuse'),
                              'detail_pane':
                              ('netprofile_core.views', 'dpane_simple'),
                              'create_wizard':
                              SimpleWizard(title=_('Add new IPv4 address'))
                          }
                      })
    id = Column('ipaddrid',
                UInt32(),
                Sequence('ipaddr_def_ipaddrid_seq'),
                Comment('IPv4 address ID'),
                primary_key=True,
                nullable=False,
                info={'header_string': _('ID')})
    host_id = Column('hostid',
                     UInt32(),
                     ForeignKey('hosts_def.hostid',
                                name='ipaddr_def_fk_hostid',
                                onupdate='CASCADE',
                                ondelete='CASCADE'),
                     Comment('Host ID'),
                     nullable=False,
                     info={
                         'header_string': _('Host'),
                         'filter_type': 'none',
                         'column_flex': 1
                     })
    pool_id = Column('poolid',
                     UInt32(),
                     ForeignKey('ippool_def.poolid',
                                name='ipaddr_def_fk_poolid',
                                onupdate='CASCADE',
                                ondelete='SET NULL'),
                     Comment('IP address pool ID'),
                     nullable=True,
                     default=None,
                     server_default=text('NULL'),
                     info={
                         'header_string': _('Pool'),
                         'filter_type': 'nplist'
                     })
    network_id = Column('netid',
                        UInt32(),
                        ForeignKey('nets_def.netid',
                                   name='ipaddr_def_fk_netid',
                                   onupdate='CASCADE',
                                   ondelete='CASCADE'),
                        Comment('Network ID'),
                        nullable=False,
                        info={
                            'header_string': _('Network'),
                            'filter_type': 'nplist'
                        })
    offset = Column(UInt32(),
                    Comment('Offset from network start'),
                    nullable=False,
                    info={'header_string': _('Offset')})
    hardware_address = Column('hwaddr',
                              MACAddress(),
                              Comment('Hardware address'),
                              nullable=False,
                              info={
                                  'header_string': _('Hardware Address'),
                                  'column_flex': 1
                              })
    ttl = Column(UInt32(),
                 Comment('RR time to live'),
                 nullable=True,
                 default=None,
                 server_default=text('NULL'),
                 info={'header_string': _('RR Time To Live')})
    visibility = Column('vis',
                        ObjectVisibility.db_type(),
                        Comment('IPv4 address visibility'),
                        nullable=False,
                        default=ObjectVisibility.both,
                        server_default=ObjectVisibility.both,
                        info={'header_string': _('Visibility')})
    owned = Column(NPBoolean(),
                   Comment('Is statically assigned?'),
                   nullable=False,
                   default=False,
                   server_default=npbool(False),
                   info={'header_string': _('Assigned')})
    in_use = Column('inuse',
                    NPBoolean(),
                    Comment('Is this IPv4 address in use?'),
                    nullable=False,
                    default=False,
                    server_default=npbool(False),
                    info={'header_string': _('In Use')})

    host = relationship('Host',
                        innerjoin=True,
                        lazy='joined',
                        backref=backref('ipv4_addresses',
                                        cascade='all, delete-orphan',
                                        passive_deletes=True))
    pool = relationship('IPPool',
                        backref=backref('ipv4_addresses',
                                        passive_deletes=True))
    network = relationship('Network',
                           innerjoin=True,
                           backref=backref('ipv4_addresses',
                                           cascade='all, delete-orphan',
                                           passive_deletes=True))

    @property
    def address(self):
        if self.network and self.network.ipv4_address:
            return self.network.ipv4_address + self.offset

    @property
    def ptr_name(self):
        addr = self.address
        if addr:
            return int(addr) % 256

    def __str__(self):
        if self.network and self.network.ipv4_address:
            return str(self.network.ipv4_address + self.offset)
Exemple #13
0
class AccessBlock(Base):
	"""
	Access block entry object.
	"""
	__tablename__ = 'accessblock_def'
	__table_args__ = (
		Comment('Access entity blocks'),
		Index('accessblock_def_i_entityid', 'entityid'),
		Index('accessblock_def_i_bstate_start', 'bstate', 'startts'),
		Index('accessblock_def_i_startts', 'startts'),
		Trigger('before', 'insert', 't_accessblock_def_bi'),
		Trigger('before', 'update', 't_accessblock_def_bu'),
		Trigger('after', 'insert', 't_accessblock_def_ai'),
		Trigger('after', 'update', 't_accessblock_def_au'),
		{
			'mysql_engine'  : 'InnoDB',
			'mysql_charset' : 'utf8',
			'info'          : {
				'cap_menu'      : 'BASE_ENTITIES', # FIXME
				'cap_read'      : 'ENTITIES_LIST', # FIXME
				'cap_create'    : 'ENTITIES_EDIT', # FIXME
				'cap_edit'      : 'ENTITIES_EDIT', # FIXME
				'cap_delete'    : 'ENTITIES_EDIT', # FIXME

				'menu_name'     : _('Access Blocks'),
				'default_sort'  : ({ 'property': 'startts' ,'direction': 'ASC' },),
				'grid_view'     : ('abid', 'entity', 'startts', 'endts', 'bstate'),
				'grid_hidden'   : ('abid',),
				'form_view'     : ('entity', 'startts', 'endts', 'bstate', 'oldstate'),
				'detail_pane'   : ('netprofile_core.views', 'dpane_simple'),
				'create_wizard' : SimpleWizard(title=_('Add new access block'))
			}
		}
	)
	id = Column(
		'abid',
		UInt32(),
		Sequence('accessblock_def_abid_seq'),
		Comment('Access block ID'),
		primary_key=True,
		nullable=False,
		info={
			'header_string' : _('ID')
		}
	)
	entity_id = Column(
		'entityid',
		UInt32(),
		Comment('Access entity ID'),
		ForeignKey('entities_access.entityid', name='accessblock_def_fk_entityid', ondelete='CASCADE', onupdate='CASCADE'),
		nullable=False,
		info={
			'header_string' : _('Account'),
			'column_flex'   : 2,
			'filter_type'   : 'none'
		}
	)
	start = Column(
		'startts',
		TIMESTAMP(),
		Comment('Start of block'),
		CurrentTimestampDefault(),
		nullable=False,
		info={
			'header_string' : _('Start'),
			'column_flex'   : 1
		}
	)
	end = Column(
		'endts',
		TIMESTAMP(),
		Comment('End of block'),
		nullable=False,
		info={
			'header_string' : _('End'),
			'column_flex'   : 1
		}
	)
	state = Column(
		'bstate',
		AccessBlockState.db_type(),
		Comment('Block state'),
		nullable=False,
		default=AccessBlockState.expired,
		server_default=AccessBlockState.expired,
		info={
			'header_string' : _('State')
		}
	)
	old_entity_state = Column(
		'oldstate',
		UInt8(),
		Comment('Old entity state'),
		nullable=False,
		default=0,
		server_default=text('0'),
		info={
			'header_string' : _('Access State')
		}
	)

	def __str__(self):
		# FIXME: use datetime range with formats
		return '%s:' % str(self.entity)
Exemple #14
0
class PerUserRateModifier(Base):
	"""
	Per-user rate modifier definition
	"""
	__tablename__ = 'rates_mods_peruser'
	__table_args__ = (
		Comment('Per-user rate modifiers'),
		Index('rates_mods_peruser_u_mapping', 'rmtid', 'entityid', 'rateid', unique=True),
		Index('rates_mods_peruser_i_entityid', 'entityid'),
		Index('rates_mods_peruser_i_rateid', 'rateid'),
		Index('rates_mods_peruser_i_l_ord', 'l_ord'),
		Trigger('before', 'insert', 't_rates_mods_peruser_bi'),
		{
			'mysql_engine'  : 'InnoDB',
			'mysql_charset' : 'utf8',
			'info'          : {
				'cap_menu'      : 'BASE_ENTITIES', # FIXME
				'cap_read'      : 'ENTITIES_LIST', # FIXME
				'cap_create'    : 'ENTITIES_EDIT', # FIXME
				'cap_edit'      : 'ENTITIES_EDIT', # FIXME
				'cap_delete'    : 'ENTITIES_EDIT', # FIXME
				'menu_name'     : _('Rate Modifiers'),
				'default_sort'  : ({ 'property': 'l_ord', 'direction': 'ASC' },),
				'grid_view'     : ('rmid', 'entity', 'rate', 'type', 'enabled', 'l_ord'),
				'grid_hidden'   : ('rmid',),
				'create_wizard' : SimpleWizard(title=_('Add new rate modifier'))
			}
		}
	)
	id = Column(
		'rmid',
		UInt32(),
		Sequence('rates_mods_peruser_rmid_seq'),
		Comment('Rate modifier ID'),
		primary_key=True,
		nullable=False,
		info={
			'header_string' : _('ID')
		}
	)
	type_id = Column(
		'rmtid',
		UInt32(),
		Comment('Rate modifier type ID'),
		ForeignKey('rates_mods_types.rmtid', name='rates_mods_peruser_fk_rmtid', ondelete='CASCADE', onupdate='CASCADE'),
		nullable=False,
		info={
			'header_string' : _('Type'),
			'filter_type'   : 'nplist',
			'column_flex'   : 1
		}
	)
	entity_id = Column(
		'entityid',
		UInt32(),
		Comment('Access entity ID'),
		ForeignKey('entities_access.entityid', name='rates_mods_peruser_fk_entityid', ondelete='CASCADE', onupdate='CASCADE'),
		nullable=False,
		info={
			'header_string' : _('Account'),
			'filter_type'   : 'none',
			'column_flex'   : 1
		}
	)
	rate_id = Column(
		'rateid',
		UInt32(),
		Comment('Rate ID'),
		ForeignKey('rates_def.rateid', name='rates_mods_peruser_fk_rateid', ondelete='CASCADE', onupdate='CASCADE'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Rate'),
			'filter_type'   : 'nplist',
			'column_flex'   : 1
		}
	)
	creation_time = Column(
		'ctime',
		TIMESTAMP(),
		Comment('Creation timestamp'),
		nullable=True,
		default=None,
		server_default=FetchedValue(),
		info={
			'header_string' : _('Created'),
			'read_only'     : True
		}
	)
	enabled = Column(
		NPBoolean(),
		Comment('Is modifier enabled?'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Enabled')
		}
	)
	lookup_order = Column(
		'l_ord',
		UInt16(),
		Comment('Lookup order'),
		nullable=False,
		default=1000,
		server_default=text('1000'),
		info={
			'header_string' : _('Lookup Order')
		}
	)

	type = relationship(
		'RateModifierType',
		innerjoin=True,
		backref=backref(
			'per_user_modifiers',
			cascade='all, delete-orphan',
			passive_deletes=True
		)
	)
	entity = relationship(
		'AccessEntity',
		innerjoin=True,
		backref=backref(
			'rate_modifiers',
			cascade='all, delete-orphan',
			passive_deletes=True
		)
	)
	rate = relationship(
		'Rate',
		backref=backref(
			'per_user_modifiers',
			cascade='all, delete-orphan',
			passive_deletes=True
		)
	)
Exemple #15
0
class AccessEntity(Entity):
	"""
	Access entity object.
	"""
	DN_ATTR = 'uid'
	__tablename__ = 'entities_access'
	__table_args__ = (
		Comment('Access entities'),
		Index('entities_access_i_stashid', 'stashid'),
		Index('entities_access_i_rateid', 'rateid'),
		Index('entities_access_i_aliasid', 'aliasid'),
		Index('entities_access_i_ipaddrid', 'ipaddrid'),
		Index('entities_access_i_ip6addrid', 'ip6addrid'),
		Index('entities_access_i_nextrateid', 'nextrateid'),
		Trigger('before', 'insert', 't_entities_access_bi'),
		Trigger('before', 'update', 't_entities_access_bu'),
		Trigger('after', 'update', 't_entities_access_au'),
		Trigger('after', 'delete', 't_entities_access_ad'),
		{
			'mysql_engine'  : 'InnoDB',
			'mysql_charset' : 'utf8',
			'info'          : {
				'cap_menu'     : 'BASE_ENTITIES',
				'cap_read'     : 'ENTITIES_LIST',
				'cap_create'   : 'ENTITIES_CREATE',
				'cap_edit'     : 'ENTITIES_EDIT',
				'cap_delete'   : 'ENTITIES_DELETE',

				'show_in_menu' : 'modules',
				'menu_name'    : _('Access Entities'),
				'menu_parent'  : 'entities',
				'default_sort' : ({ 'property': 'nick' ,'direction': 'ASC' },),
				'grid_view'    : (
					MarkupColumn(
						name='icon',
						header_string=' ',
						help_text=_('Entity icon'),
						column_width=22,
						column_name=_('Icon'),
						column_resizable=False,
						cell_class='np-nopad',
						template='<img class="np-block-img" src="{grid_icon}" />'
					),
					'entityid',
					'nick', 'stash', 'rate'
				),
				'grid_hidden'  : ('entityid',),
				'form_view'    : (
					'nick', 'parent', 'state', 'flags',
					'password', 'stash', 'rate', 'next_rate', #'alias_of',
					'ipv4_address', 'ipv6_address',
					'ut_ingress', 'ut_egress', 'u_sec',
					'qpend', 'access_state',
					'pol_ingress', 'pol_egress',
					'bcheck', 'pcheck',
					'descr'
				),
				'easy_search'  : ('nick',),
				'extra_data'    : ('grid_icon',),
				'detail_pane'  : ('netprofile_core.views', 'dpane_simple'),
				'create_wizard' : Wizard(
					Step(
						'nick', 'parent', 'state', 
						'flags', 'descr',
						id='generic', title=_('Generic entity properties'),
					),
					Step(
						'password', 'stash', 'rate',
						id='ent_access1', title=_('Access entity properties'),
					),
					title=_('Add new access entity'), validator='CreateAccessEntity'
				)
			}
		}
	)
	__mapper_args__ = {
		'polymorphic_identity' : 5
	}
	id = Column(
		'entityid',
		UInt32(),
		ForeignKey('entities_def.entityid', name='entities_access_fk_entityid', ondelete='CASCADE', onupdate='CASCADE'),
		Comment('Entity ID'),
		primary_key=True,
		nullable=False,
		info={
			'header_string' : _('ID')
		}
	)
	password = Column(
		Unicode(255),
		Comment('Cleartext password'),
		nullable=False,
		info={
			'header_string' : _('Password'),
			'secret_value'  : True,
			'editor_xtype'  : 'passwordfield'
		}
	)
	stash_id = Column(
		'stashid',
		UInt32(),
		ForeignKey('stashes_def.stashid', name='entities_access_fk_stashid', onupdate='CASCADE'),
		Comment('Used stash ID'),
		nullable=False,
		info={
			'header_string' : _('Stash'),
			'column_flex'   : 3
		}
	)
	rate_id = Column(
		'rateid',
		UInt32(),
		ForeignKey('rates_def.rateid', name='entities_access_fk_rateid', onupdate='CASCADE'),
		Comment('Used rate ID'),
		nullable=False,
		info={
			'header_string' : _('Rate'),
			'filter_type'   : 'nplist',
			'column_flex'   : 2
		}
	)
	alias_of_id = Column(
		'aliasid',
		UInt32(),
		ForeignKey('entities_access.entityid', name='entities_access_fk_aliasid', ondelete='CASCADE', onupdate='CASCADE'),
		Comment('Aliased access entity ID'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Alias Of'),
			'filter_type'   : 'none'
		}
	)
	next_rate_id = Column(
		'nextrateid',
		UInt32(),
		ForeignKey('rates_def.rateid', name='entities_access_fk_nextrateid', ondelete='SET NULL', onupdate='CASCADE'),
		Comment('Next rate ID'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Next Rate'),
			'filter_type'   : 'nplist'
		}
	)
	ipv4_address_id = Column(
		'ipaddrid',
		UInt32(),
		ForeignKey('ipaddr_def.ipaddrid', name='entities_access_fk_ipaddrid', ondelete='SET NULL', onupdate='CASCADE'),
		Comment('IPv4 address ID'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('IPv4 Address')
		}
	)
	ipv6_address_id = Column(
		'ip6addrid',
		UInt64(),
		ForeignKey('ip6addr_def.ip6addrid', name='entities_access_fk_ip6addrid', ondelete='SET NULL', onupdate='CASCADE'),
		Comment('IPv6 address ID'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('IPv6 Address')
		}
	)
	used_traffic_ingress = Column(
		'ut_ingress',
		Traffic(),
		Comment('Used ingress traffic'),
		nullable=False,
		default=0,
		server_default=text('0'),
		info={
			'header_string' : _('Used Ingress'),
			'read_only'     : True
		}
	)
	used_traffic_egress = Column(
		'ut_egress',
		Traffic(),
		Comment('Used egress traffic'),
		nullable=False,
		default=0,
		server_default=text('0'),
		info={
			'header_string' : _('Used Egress'),
			'read_only'     : True
		}
	)
	used_seconds = Column(
		'u_sec',
		UInt32(),
		Comment('Used seconds'),
		nullable=False,
		default=0,
		server_default=text('0'),
		info={
			'header_string' : _('Used Seconds'),
			'read_only'     : True
		}
	)
	quota_period_end = Column(
		'qpend',
		TIMESTAMP(),
		Comment('End of quota period'),
		nullable=True,
		default=None,
		server_default=FetchedValue(),
		info={
			'header_string' : _('Ends'),
			'read_only'     : True
		}
	)
	access_state = Column(
		'state',
		UInt8(),
		Comment('Access code'),
		nullable=False,
		default=0,
		server_default=text('0'),
		info={
			'header_string' : _('Access Code'),
			'choices'       : AccessState,
			'write_cap'     : 'ENTITIES_ACCOUNTSTATE_EDIT'
		}
	)
	policy_ingress = Column(
		'pol_ingress',
		ASCIIString(255),
		Comment('Ingress traffic policy'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Ingress Policy')
		}
	)
	policy_egress = Column(
		'pol_egress',
		ASCIIString(255),
		Comment('Egress traffic policy'),
		nullable=True,
		default=None,
		server_default=text('NULL'),
		info={
			'header_string' : _('Egress Policy')
		}
	)
	check_block_state = Column(
		'bcheck',
		NPBoolean(),
		Comment('Check block state'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Check Blocks')
		}
	)
	check_paid_services = Column(
		'pcheck',
		NPBoolean(),
		Comment('Check paid services'),
		nullable=False,
		default=False,
		server_default=npbool(False),
		info={
			'header_string' : _('Check Services')
		}
	)

	stash = relationship(
		'Stash',
		innerjoin=True,
		backref='access_entities'
	)
	rate = relationship(
		'Rate',
		innerjoin=True,
		foreign_keys=rate_id,
		backref='access_entities'
	)
	next_rate = relationship(
		'Rate',
		foreign_keys=next_rate_id,
		backref=backref(
			'pending_access_entities',
			passive_deletes=True
		)
	)
	alias_of = relationship(
		'AccessEntity',
		foreign_keys=alias_of_id,
		remote_side=[id],
		backref='aliases'
	)
	ipv4_address = relationship(
		'IPv4Address',
		backref=backref(
			'access_entities',
			passive_deletes=True
		)
	)
	ipv6_address = relationship(
		'IPv6Address',
		backref=backref(
			'access_entities',
			passive_deletes=True
		)
	)
	blocks = relationship(
		'AccessBlock',
		backref=backref('entity', innerjoin=True),
		cascade='all, delete-orphan',
		passive_deletes=True
	)

	def data(self, req):
		ret = super(AccessEntity, self).data

		if self.rate:
			ret['rate'] = str(self.rate)
		if self.next_rate:
			ret['nextrate'] = str(self.next_rate)
		if self.quota_period_end:
			ret['qpend'] = format_datetime(self.quota_period_end, locale=req.current_locale)

		ret['accessstate'] = self.access_state_string(req)
		if self.access_state == AccessState.ok.value:
			ret['accessimg'] = 'ok'
		elif self.access_state == AccessState.block_auto.value:
			ret['accessimg'] = 'stop'
		elif self.access_state == AccessState.block_manual.value:
			ret['accessimg'] = 'manual'
		else:
			ret['accessimg'] = 'misc'

		return ret

	def access_state_string(self, req):
		if self.access_state is None:
			return None
		return req.localizer.translate(AccessState.from_string(self.access_state).description)

	def grid_icon(self, req):
		return req.static_url('netprofile_access:static/img/access.png')
Exemple #16
0
class ExternalOperation(Base):
    """
	External operation object.
	"""

    __tablename__ = 'xop_def'
    __table_args__ = (Comment('External operations'),
                      Index('xop_def_i_extid',
                            'extid'), Index('xop_def_i_xoppid', 'xoppid'),
                      Index('xop_def_i_ts',
                            'ts'), Index('xop_def_i_entityid', 'entityid'),
                      Index('xop_def_i_stashid', 'stashid'),
                      Index('xop_def_u_sioid', 'sioid', unique=True),
                      Trigger('before', 'insert', 't_xop_def_bi'),
                      Trigger('before', 'update', 't_xop_def_bu'), {
                          'mysql_engine': 'InnoDB',
                          'mysql_charset': 'utf8',
                          'info': {
                              'cap_menu':
                              'BASE_XOP',
                              'cap_read':
                              'STASHES_IO',
                              'cap_create':
                              'STASHES_IOTYPES_CREATE',
                              'cap_edit':
                              '__NOPRIV__',
                              'cap_delete':
                              '__NOPRIV__',
                              'menu_name':
                              _('External Operations'),
                              'menu_main':
                              True,
                              'show_in_menu':
                              'modules',
                              'default_sort': ({
                                  'property': 'ts',
                                  'direction': 'DESC'
                              }, ),
                              'grid_view':
                              ('xopid', 'provider', 'ts', 'entity', 'currency',
                               'diff', 'state'),
                              'grid_hidden': ('xopid', 'currency'),
                              'form_view':
                              ('provider', 'ts', 'entity', 'currency', 'diff',
                               'state', 'stash', 'stash_io', 'extid', 'eacct'),
                              'easy_search': ('extid', 'eacct'),
                              'extra_data': ('formatted_difference', ),
                              'detail_pane':
                              ('netprofile_core.views', 'dpane_simple')
                          }
                      })
    id = Column('xopid',
                UInt32(),
                Sequence('xop_def_xopid_seq'),
                Comment('External operation ID'),
                primary_key=True,
                nullable=False,
                info={'header_string': _('ID')})
    external_id = Column('extid',
                         ASCIIString(255),
                         Comment('Remote provider operation ID'),
                         nullable=True,
                         default=None,
                         server_default=text('NULL'),
                         info={'header_string': _('External ID')})
    external_account = Column('eacct',
                              Unicode(255),
                              Comment('External account name'),
                              nullable=True,
                              default=None,
                              server_default=text('NULL'),
                              info={'header_string': _('External Account')})
    provider_id = Column('xoppid',
                         UInt32(),
                         ForeignKey('xop_providers.xoppid',
                                    name='xop_def_fk_xoppid',
                                    onupdate='CASCADE'),
                         Comment('External operation provider ID'),
                         nullable=False,
                         info={
                             'header_string': _('Provider'),
                             'column_flex': 3
                         })
    currency_id = Column(
        'currid',
        UInt32(),
        Comment('Currency ID'),
        ForeignKey('currencies_def.currid',
                   name='xop_def_fk_currid',
                   onupdate='CASCADE'),  # ondelete=RESTRICT
        nullable=True,
        default=None,
        server_default=text('NULL'),
        info={
            'header_string': _('Currency'),
            'filter_type': 'nplist'
        })
    timestamp = Column('ts',
                       TIMESTAMP(),
                       Comment('Timestamp of operation'),
                       CurrentTimestampDefault(on_update=True),
                       nullable=False,
                       info={'header_string': _('Date')})
    entity_id = Column('entityid',
                       UInt32(),
                       ForeignKey('entities_def.entityid',
                                  name='xop_def_fk_entityid',
                                  onupdate='CASCADE',
                                  ondelete='SET NULL'),
                       Comment('Entity ID'),
                       nullable=True,
                       default=None,
                       server_default=text('NULL'),
                       info={
                           'header_string': _('Entity'),
                           'filter_type': 'none',
                           'column_flex': 3
                       })
    stash_id = Column('stashid',
                      UInt32(),
                      ForeignKey('stashes_def.stashid',
                                 name='xop_def_fk_stashid',
                                 onupdate='CASCADE',
                                 ondelete='SET NULL'),
                      Comment('Affected stash ID'),
                      nullable=True,
                      default=None,
                      server_default=text('NULL'),
                      info={
                          'header_string': _('Stash'),
                          'filter_type': 'none',
                          'column_flex': 3
                      })
    stash_io_id = Column('sioid',
                         UInt32(),
                         ForeignKey('stashes_io_def.sioid',
                                    name='xop_def_fk_sioid',
                                    onupdate='CASCADE',
                                    ondelete='SET NULL'),
                         Comment('Related stash operation ID'),
                         nullable=True,
                         default=None,
                         server_default=text('NULL'),
                         info={
                             'header_string': _('Operation'),
                             'filter_type': 'none'
                         })
    difference = Column('diff',
                        Money(),
                        Comment('Stash amount changes'),
                        nullable=False,
                        default=0,
                        server_default=text('0.0'),
                        info={
                            'header_string': _('Amount'),
                            'column_xtype': 'templatecolumn',
                            'template': '{formatted_difference}'
                        })
    state = Column(ExternalOperationState.db_type(),
                   Comment('Operation state'),
                   nullable=False,
                   default=ExternalOperationState.new,
                   server_default=ExternalOperationState.new,
                   info={'header_string': _('State')})

    provider = relationship('ExternalOperationProvider',
                            innerjoin=True,
                            backref=backref('external_operations',
                                            passive_deletes='all'))
    currency = relationship('Currency',
                            lazy='joined',
                            backref=backref('external_operations',
                                            passive_deletes='all'))
    entity = relationship('Entity',
                          backref=backref('external_operations',
                                          passive_deletes=True))
    stash = relationship('Stash',
                         backref=backref('external_operations',
                                         passive_deletes=True))
    stash_io = relationship('StashIO',
                            backref=backref('external_operations',
                                            passive_deletes=True))

    @validates('state')
    def _valid_state(self, key, val):
        if val not in ExternalOperationState:
            raise ValueError('Invalid XOP state')
        if (self.state is None) or (self.state == val):
            return val
        if self.state in (ExternalOperationState.new,
                          ExternalOperationState.pending):
            if val in (ExternalOperationState.checked,
                       ExternalOperationState.confirmed,
                       ExternalOperationState.canceled):
                return val
            raise ValueError('Invalid XOP state transition')
        if self.state == ExternalOperationState.checked:
            if val in (ExternalOperationState.pending,
                       ExternalOperationState.canceled):
                return val
            raise ValueError('Invalid XOP state transition')
        if self.state == ExternalOperationState.confirmed:
            if val in (ExternalOperationState.cleared,
                       ExternalOperationState.canceled):
                return val
            raise ValueError('Invalid XOP state transition')
        raise ValueError('Invalid XOP state')

    def __str__(self):
        return '%s %s' % (self.provider, self.external_id)

    def formatted_difference(self, req):
        return money_format(req, self.difference, currency=self.currency)