Обработчик активации сервисов для Cisco(управление доступом по acl)

Материал из BiTel WiKi

(Различия между версиями)
Перейти к: навигация, поиск
Stark (Обсуждение | вклад)
(Новая страница: «Изначально получен из скриптового шлюза IPN подобного этому: http://wiki.bgbilling.ru/index.php/%D0%A8%D0%BB%D1%8E%D…»)

Текущая версия на 10:30, 20 декабря 2012

Изначально получен из скриптового шлюза IPN подобного этому: http://wiki.bgbilling.ru/index.php/%D0%A8%D0%BB%D1%8E%D0%B7_Cisco2,_%D1%83%D1%87%D0%B8%D1%82%D1%8B%D0%B2%D0%B0%D1%8E%D1%89%D0%B8%D0%B9_%D0%BF%D0%B5%D1%80%D0%B8%D0%BE%D0%B4%D1%8B_%D0%B4%D0%B5%D0%B9%D1%81%D1%82%D0%B2%D0%B8%D1%8F_%D0%B4%D0%B8%D0%BF%D0%B0%D0%B7%D0%BE%D0%BD%D0%BE%D0%B2

Для поддержки макросов из команд шлюза IPN ( <LOOP_NET></LOOP_NET> и т.п) используется класс InetDeviceCommandUtils . Сами команды заводятся в коде самого класса обработчика.


Код обработчика

package ru.maglan.bgbilling.modules.inet.dyn.device.cisco;
 
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
 
import org.apache.log4j.Logger;
 
import ru.bitel.bgbilling.common.BGException;
import ru.bitel.bgbilling.modules.inet.access.sa.ServiceActivator;
import ru.bitel.bgbilling.modules.inet.access.sa.ServiceActivatorAdapter;
import ru.bitel.bgbilling.modules.inet.access.sa.ServiceActivatorEvent;
import ru.bitel.bgbilling.modules.inet.api.common.bean.InetDevice;
import ru.bitel.bgbilling.modules.inet.api.common.bean.InetDeviceType;
import ru.bitel.bgbilling.modules.inet.api.common.bean.InetServ;
import ru.bitel.bgbilling.modules.inet.api.server.bean.InetDeviceCommandUtils;
import ru.bitel.bgbilling.server.util.Setup;
import ru.bitel.common.ParameterMap;
import ru.bitel.common.inet.IpAddress;
import ru.bitel.common.inet.IpNet;
import bitel.billing.common.IPUtils;
import bitel.billing.server.util.telnet.TelnetSession;
 
public class CiscoServiceActivator
	extends ServiceActivatorAdapter
	implements ServiceActivator
{
	private static Logger log = Logger.getLogger( CiscoServiceActivator.class );
 
	private static final  String COMMANDS = 
 
		"[OPEN]" +
 
		 //"<LOOP_NET>" + 
		 "access-template bgb-in dynamic-in {IP} {MASK_WILD} any\n" + 
		 "access-template bgb-out dynamic-out any {IP} {MASK_WILD}\n" +
		 //"</LOOP_NET>" +
 
 
		 "[/OPEN]" +
 
		 "[CLOSE]" +
 
		 //"<LOOP_NET>" + 
		 "clear access-template bgb-in dynamic-in {IP} {MASK_WILD} any\n" + 
		 "clear access-template bgb-out dynamic-out any {IP} {MASK_WILD}\n" +
		 //"</LOOP_NET>" +
 
		 "[/CLOSE]";
 
	private static Pattern OPEN_PATTERN = Pattern.compile( "\\[OPEN\\](.*)\\[/OPEN\\]", Pattern.DOTALL );
	private static Pattern CLOSE_PATTERN = Pattern.compile( "\\[CLOSE\\](.*)\\[/CLOSE\\]", Pattern.DOTALL );
	private static Pattern DELETE_PATTERN = Pattern.compile( "\\[DELETE\\](.*)\\[/DELETE\\]", Pattern.DOTALL );
 
	private InetDevice inetDevice;
	private ParameterMap config;
	private TelnetSession session;
	private StringBuffer result;
 
	@Override
	public Object init( Setup setup, int moduleId, InetDevice device, InetDeviceType deviceType, ParameterMap config )
		throws Exception
	{
		this.inetDevice = device;
		this.config = config;
		return true;				
	}
 
 
	@Override
	public Object connect()
		throws Exception
	{
		log.info( "start of cisco........................................................");
		List<InetSocketAddress> hosts = inetDevice.getHosts();
		String host = hosts.get( 0 ).getHostName();
		int port = hosts.get( 0 ).getPort();
 
		String login = inetDevice.getUsername();
		String pswd = inetDevice.getPassword();
 
		if( log.isDebugEnabled() )
		{
			log.debug( " gate: " + host + ":" + port + " login: " + login + " pswd: " + pswd );
		}
 
	    int timeout = config.getInt( "timeout", 0 );
 
	    result = new StringBuffer();	 
 
		if( log.isDebugEnabled() )
		{
			log.debug( inetDevice.getId() + " gate: " + host + ":" + port  + " login: " + login + " pswd: " + 		 pswd );
		}
 
	 	log.info( "before connect.." );
 
		session = new TelnetSession( host, port);
	    session.setTimeout( timeout );
		session.setEndString( ":" );						
		result.append( session.connect() );
		log.info( "after connect.." );
 
		result.append( session.doCommand( login ) );
		log.info( "after login.." );
 
		session.setEndString( "#" );
		result.append( session.doCommand( pswd ) );
 
		log.info( "after pswd.." );
 
		result.append( session.doCommand( "terminal length 0" ) );
		result.append( session.doCommand( "terminal width 0" ) ); 
 
		return true;
 
	}
 
	@Override
	public Object disconnect()
		throws Exception
	{
		////
		//result.append( session.doCommand( "exit" ) );
	    session.doCommandAsync( "exit" );
	    session.disconnect();
 
		log.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
		log.info( result );
		log.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");		
 
		log.debug( "ok" );
 
 
		log.info( "end of cisco........................................................");
		return true;
	}
 
 
 
	@Override
	public Object serviceModify( ServiceActivatorEvent serviceActivatorEvent )
		throws Exception
	{		
		InetServ serv = serviceActivatorEvent.getNewInetServ();
		proccesServ( serviceActivatorEvent, serv, false );
 
 
		return null;
	}
 
	private Object proccesServ( ServiceActivatorEvent serviceActivatorEvent, InetServ serv, boolean syncAnyway )
    	throws BGException, Exception
	{
		Set<Integer> oldOptions = serviceActivatorEvent.getOldOptions();
		Set<Integer> newOptions = serviceActivatorEvent.getNewOptions();
 
		log.debug( "oldState=" + serviceActivatorEvent.getOldState() + ";" + "newState=" + serviceActivatorEvent.getNewState() );
		log.debug( "oldOptions=" + oldOptions + ";" + "newOptions=" + newOptions );
 
		log.debug( "state!=state " + ( serviceActivatorEvent.getNewState() != serviceActivatorEvent.getOldState() ) );
 
		if( serviceActivatorEvent.getNewState() != serviceActivatorEvent.getOldState() || !oldOptions.equals( newOptions ) || syncAnyway )						
		{									
			log.debug( "execute commands" );
			//doCommands( session, result);
 
			//String accessList100 = session.doCommand( "show access-list bgb-in" ); 
			//result.append( accessList100 );
			//String accessList101 = session.doCommand( "show access-list bgb-out" ); 
			//result.append( accessList101 );
 
			//for( UserStatus status : statusList )
			//{
 
				int contractId = serv.getContractId();
 
				int state = serviceActivatorEvent.getNewState();
 
				log.info(" begin new cid = " +  contractId );
 
 
				String rules[] = null;
 
				if( state == InetServ.STATE_ENABLE )
				{						
					rules = getRules( serv, OPEN_PATTERN );
				} 				
				else 
				{						
					rules = getRules( serv, CLOSE_PATTERN );
				}		
 
				for ( String rule : rules )
				{									
					log.debug( "rule="+ rule );
					result.append(  session.doCommand( rule ) );				
				}
 
 
				log.info(" end  cid = " +  contractId );
		}
 
		return null;
	}
 
	private String [] getRules( InetServ serv,  Pattern pattern  )
	{
 
 
	   Map<String, String> replacements = new HashMap<String, String>();
 
 
	   int maskBit = IpNet.getMask( serv.getAddressFrom(), serv.getAddressTo() );	   
	   long mask = ( 0xFFFFFFFFl << ( 32 - maskBit ) ) & 0xFFFFFFFFl;						
	   long maskWild = mask ^ 0xFFFFFFFFl;
 
	   replacements.put( "\\{IP\\}", IpAddress.toString( serv.getAddressFrom() ) );
	   replacements.put( "\\{MASK_WILD\\}", IPUtils.convertLongIpToString(  maskWild ) );
 
	   String result = InetDeviceCommandUtils.generateCommands( COMMANDS, pattern, new ArrayList<String>(), replacements, "" );
 
 
	   result = result.replaceAll( "\r", "" );
 
	   //GateCommandUtil.
 
	   return result.split( "\n" );
	}
 
 
	public Object serviceCreate( ServiceActivatorEvent e )
    throws Exception
	{
	    log.debug( "serviceCreate" );	    	    
	    return serviceModify( e );	    
	}
 
	@Override
	public Object serviceCancel( ServiceActivatorEvent e )
	    throws Exception
	{
	    log.debug( "serviceCancel" );
	    InetServ serv = e.getOldInetServ();		
	    return proccesServ( e, serv, true );
	}
 
 
}
Личные инструменты