Реализация обработчика активации сервисов для коммутаторов DES-3526, DES-3550, DES-3828, DES-3852, DGS-3200-10 и им подобных

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

Версия от 09:36, 31 августа 2012; Stark (Обсуждение | вклад)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Этот обработчик получен из скриптового шлюза IPN:

http://wiki.bgbilling.ru/index.php/%D0%A0%D0%B5%D0%B0%D0%BB%D0%B8%D0%B0%D0%B7%D0%B0%D1%86%D0%B8%D1%8F_%D1%81%D0%BA%D1%80%D0%B8%D0%BF%D1%82%D0%BE%D0%B2%D0%B3%D0%BE_%D1%88%D0%BB%D1%8E%D0%B7%D0%B0_%D0%B4%D0%BB%D1%8F_%D0%BA%D0%BE%D0%BC%D0%BC%D1%83%D1%82%D0%B0%D1%82%D0%BE%D1%80%D0%BE%D0%B2_DES-3526,_DES-3550,_DES-3828,_DES-3852,_DGS-3200-10_%D0%B8_%D0%B8%D0%BC_%D0%BF%D0%BE%D0%B4%D0%BE%D0%B1%D0%BD%D1%8B%D1%85

в процессе перехода с IPN на INET.

Настройка сервиса, устройства и типа устройства описана тут : http://wiki.bgbilling.ru/index.php/%D0%9A%D0%BE%D0%BD%D0%B2%D0%B5%D1%80%D1%82%D0%B5%D1%80:_%D1%88%D0%BB%D1%8E%D0%B7%D1%8B(%D0%B2_%D1%83%D1%81%D1%82%D1%80%D0%BE%D0%B9%D1%81%D1%82%D0%B2%D0%B0_INET),_ip-%D1%80%D0%B5c%D1%83%D1%80%D1%81%D1%8B,_%D1%82%D0%B8%D0%BF%D1%8B_%D0%BF%D1%80%D0%B0%D0%B2%D0%B8%D0%BB(%D0%B2_%D0%BE%D0%BF%D1%86%D0%B8%D0%B8_INET),_%D0%BF%D1%80%D0%B8%D0%B2%D1%8F%D0%B7%D0%BA%D1%83_%D0%B4%D0%BE%D0%B3%D0%BE%D0%B2%D0%BE%D1%80%D0%BE%D0%B2_%D0%BA_%D1%88%D0%BB%D1%8E%D0%B7%D0%B0%D0%BC(%D0%B2_%D1%81%D0%B5%D1%80%D0%B2%D0%B8%D1%81%D1%8B_Inet).%D0%A1%D1%85%D0%B5%D0%BC%D0%B0_dhcp-mikrotik-dlink/mirotik


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

package ru.gigacom.inet.dyn.device.dlink;
 
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
 
import org.apache.log4j.Logger;
 
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.server.util.Setup;
import ru.bitel.common.ParameterMap;
import ru.bitel.common.Preferences;
import ru.bitel.common.Utils;
import ru.bitel.common.inet.IpAddress;
import bitel.billing.common.module.ipn.IPNContractStatus;
import bitel.billing.server.ipn.UserStatus;
import bitel.billing.server.ipn.dlink.UserPortStatus;
import bitel.billing.server.util.telnet.TelnetSession;
 
/**
 * Dlink 3026,3028,1228ME 
 * @author stark
 *
 */
public class DlinkTelnetServiceActivator
	extends ServiceActivatorAdapter
	implements ServiceActivator
{
	private InetDevice inetDevice;
	private static final Logger log = Logger.getLogger( DlinkTelnetServiceActivator.class );
	private TelnetSession session;
	private StringBuffer result ;
	private ParameterMap parameterMap; 
 
	@Override
	public Object init( Setup setup, int moduleId, InetDevice inetDevice, InetDeviceType inetDeviceType, ParameterMap parameterMap )
		throws Exception
	{
		this.inetDevice = inetDevice;
		this.parameterMap = parameterMap;
		return true;
	}
 
	@Override
	public Object connect()
		throws Exception
	{
		List< InetSocketAddress> hosts = inetDevice.getHosts();
 
		String host = hosts.get( 0 ).getHostName();
		int port = hosts.get( 0 ).getPort();
 
		String pswd = inetDevice.getPassword();
		String login = inetDevice.getUsername();
		String enablepwd = inetDevice.getSecret();
 
 
		result = new StringBuffer();
 
 
		if( log.isDebugEnabled() )
		{
		    log.debug( inetDevice.getId() + " gate: " + host + ":" + port  + " login: " + login + " pswd: " + 		pswd );
		}
 
 
		session = new TelnetSession( host, port);
		session.setEndString( ":" );						
 
		log.debug( "before connect" );
		session.connect();		
		log.debug( "after connect" );
 
		result.append( session.doCommand( login ) );
		log.debug( "after command" );
 
		session.setEndString( "#" );
		result.append( session.doCommand( pswd ) );
		log.debug( "before pswd" );
 
		log.debug( "before enable" );
		session.setEndString( ":" );
		result.append( session.doCommand( "enable admin" ) );
		log.debug( "before enablepwd" );
		session.setEndString( "#" );
		result.append( session.doCommand( enablepwd ) );
		log.debug( "after enable" );
 
		session.setEndString( "#" );
 
		return true;
	}
 
	@Override
	public Object serviceModify( ServiceActivatorEvent serviceActivatorEvent )
		throws Exception
	{		
		log.debug( "newState= " +  serviceActivatorEvent.getNewState() );
		if ( serviceActivatorEvent.getNewState() != serviceActivatorEvent.getOldState() )
		{
			int state = serviceActivatorEvent.getNewState();
 
			try
			{
				InetServ serv = serviceActivatorEvent.getNewInetServ();
 
		        log.debug( "execute commands" );
 
				String openAddress =  parameterMap.get( "open.address",  "255.255.255.255" ) ;
 
				log.debug( "openAddress = " +  openAddress );
 
 
				List<Integer>uplinks = Utils.toListInt( parameterMap.get( "uplink", "" ) );
 
 
				//List<UserPortStatus> ports = new ArrayList<UserPortStatus>(); 
				//List ports = getUserList( statusList );
 
 
 
				String [] openRules = new String [] {
 
						//Профиль 20 Разрешаем клиенту видеть мир 
						// разрешающие правила добавляются с номером порта клиента						
						"config access_profile profile_id 20 add access_id ${port} ip source_ip ${ip} destination_ip 0.0.0.0 port ${port} permit"};
 
 
 
				String [] closeRules = new String [] {
 
					// Профиль 8 разрешаем клиенту видеть Стат+ДНС сервер
						// разрешающие правила добавляются с номером порта клиента			
						"config access_profile profile_id 8 add access_id ${port} ip source_ip ${ip} destination_ip ${openAdress} port ${port} permit",
 
						//Профиль 12 Разрешаем ИП запросы на аплинках на адрес клиента со статистики
						"config access_profile profile_id 12 add access_id ${mod}${port} ip source_ip ${openAdress} destination_ip ${ip} port ${upport} permit", 
 
 
						//16 Запрещаем ИП запросы на аплинках на адрес клиента
						"config access_profile profile_id 16 add access_id ${mod}${port} ip source_ip 0.0.0.0 destination_ip ${ip} port ${upport} deny"};
 
 
				//for( UserPortStatus port : ports )
				//{
 
 
					log.debug("port.ipAddr=" + IpAddress.toString( serv.getAddressFrom() ) );
					//удаляюшие правила 
 
					if ( state == InetServ.STATE_DELETED )
					{
 
						int [] profiles = new int [] { 8, 20 }; 
 
						for (int profile : profiles)
						{
 
							String rule = "config access_profile profile_id " + profile + " delete access_id " + serv.getInterfaceId();
							log.debug("rule=" + rule); 
							result.append(  session.doCommand( rule ) );
						}
 
						profiles = new int [] { 12, 16 };
						for (int profile : profiles)
						{
 
							for (int j = 0; j < uplinks.size(); j++)
							{
 
								Integer upport = uplinks.get(j);			
								String pref = j > 0 ? String.valueOf( j * 10 ) : "";
								String rule = "config access_profile profile_id " + profile + " delete access_id " + pref + serv.getInterfaceId();
								log.debug("rule=" + rule); 
								result.append(  session.doCommand( rule ) );
							}
						}
 
 
					} 
					else 
					if ( state == InetServ.STATE_ENABLE )			
					{
						int [] profiles = new int [] { 8 }; 
 
						for (int profile : profiles)
						{
 
							String rule = "config access_profile profile_id " + profile + " delete access_id " + serv.getInterfaceId();
							log.debug("rule=" + rule); 
							result.append(  session.doCommand( rule ) );
						}
 
						profiles = new int [] { 12, 16 };
						for (int profile : profiles)
						{
 
							for (int j = 0; j < uplinks.size(); j++)
							{
 
								Integer upport = uplinks.get(j);			
								String pref = j > 0 ? String.valueOf( j * 10 ) : "";
								String rule = "config access_profile profile_id " + profile + " delete access_id " + pref + serv.getInterfaceId();
								log.debug("rule=" + rule); 
								result.append(  session.doCommand( rule ) );
							}
						}
 
 
						//20
						String rule = openRules[0];
						rule = setValues( rule, serv.getInterfaceId(), IpAddress.toString( serv.getAddressFrom() ) , openAddress, "" );
						log.info("rule=" + rule);
						result.append(  session.doCommand( rule ) );
 
					}
					if ( state == InetServ.STATE_DISABLE )
					{
						int [] profiles = new int [] { 20 }; 
 
						for (int profile : profiles)
						{
 
							String rule = "config access_profile profile_id " + profile + " delete access_id " + serv.getInterfaceId();
							log.debug("rule=" + rule); 
							result.append(  session.doCommand( rule ) );
						}
 
 
						//8
						String rule = closeRules[0];
						rule = setValues( rule, serv.getInterfaceId(), IpAddress.toString( serv.getAddressFrom() ), openAddress, "" );
 
						log.info("rule=" + rule);
						result.append(  session.doCommand( rule ) );
 
						//12, 16
						for (int j = 0; j < uplinks.size(); j++)
						{
							Integer upport = uplinks.get(j);			
 
							for (int i = 1; i < 3; i++)
							{	
								rule = closeRules[i];
								rule = setValues( rule, serv.getInterfaceId(), IpAddress.toString( serv.getAddressFrom() ), openAddress, String.valueOf( upport ) );
								rule = rule.replaceAll( "\\$\\{mod\\}" , String.valueOf( j * 10 )  );
								log.info("rule=" + rule);
								result.append(  session.doCommand( rule ) );
							}
 
						}
 
					}		
 
			} catch (Exception e)
			{
		 		log.error( "", e );
 
			} 
		}
		return null;
	}
 
 
 
	@Override
	public Object connectionClose( ServiceActivatorEvent serviceActivatorEvent1 )
		throws Exception
	{
		return null;
	}
 
	@Override
	public Object serviceCreate( ServiceActivatorEvent serviceActivatorEvent1 )
		throws Exception
	{
		return null;
	}
 
	@Override
	public Object disconnect()
		throws Exception
	{
		session.setEndString( "#" );
        log.debug( "SAVE" );
		result.append( session.doCommand( "save" ) );
		log.debug( "AFTER SAVE" );
 
		session.setEndString ( "****" );
		result.append( session.doCommand( "logout" ) );
 
		log.info( result.toString() );
 
		log.debug( "ok" );
 
		return true;
	}
 
 
 
	private String setValues( String rule,  int port, String ip, String openAddress,  String upport )
	{
		rule = rule.replaceAll( "\\$\\{port\\}", String.valueOf( port ) );
		rule = rule.replaceAll( "\\$\\{ip\\}" , ip  );
		rule = rule.replaceAll( "\\$\\{openAdress\\}", openAddress );	
		rule = rule.replaceAll( "\\$\\{upport\\}",  upport  );
		return rule;
	}
 
}
Личные инструменты