Visualizzazione dei risultati da 1 a 8 su 8
  1. #1
    Utente di HTML.it L'avatar di morphy79
    Registrato dal
    Jun 2004
    Messaggi
    1,568

    server ftp e memoria

    aiuto sono disperato... sto modificando un server ftp free preso dal web...
    ho dei problemi relativi alla memoria...
    ogni utente che si connette al server ftp avvia un thread e da takmanager ho notato che la memoria umenta di 300 k..
    Quando però l'utente si disconnette mi scende di solo 100 k !!!!
    aiutatemi sono disperatooooo !!!!!!!!

    questa è la parte di codice relativa all'avvio del thread...

    codice:
    package server.services;
    
    import it.vegaspa.clientFXS.businessLogic.MailHelper;
    
    import java.net.*;
    import java.io.*;
    import java.util.*;
    
    import server.*;
    import server.event.*;
    
    public class Dock implements Runnable{
    	
      private long sessionNr = Conf.getSession();
      private Thread th;
      private ServerSocket ss;
      private static BigBrother bb = BigBrother.getInstance();
    	private int maxConnections = Conf.getMaxUsers();
    	private HashSet probes = new HashSet();
    	private static HashMap users = new HashMap();
    	private HashSet obs;
    	private boolean suspended=false;
    	private boolean autoSave=false;
    	
    	public Dock( HashSet observers ){
    		obs = observers;
      }
    	
      //off as default
      public void setAutoSave(boolean on) {
      	autoSave = on;
      }
      
      public boolean doesAutoSave() {
      	return autoSave;
      }
      
      public void start(){
        suspended=false;
    		th = new Thread(this);
        th.start();
      }
      
      public boolean stop(){
    		suspended=true;
    		try{
          if (ss != null)
    				ss.close();
    			  ss = null;	
    			return true;
        }catch(IOException e){
          bb.dockException(e,"Could not stop the server.");
    			return false;
        }
      }
    	
    	public boolean isRunning() {
    		if (ss == null)
    			return false;
    		return !ss.isClosed();
    	}
    
      public synchronized void run(){
        Socket socket;
        
        // IMPOSTO INDIRIZZO IP DI DEFAULT
        String indirizzoIP = "";
        
        try{
        
          // LETTURA DA FILE DI CONFIGURAZIONE DELL'INDIRIZZO IP (se vuoto utilizzo quello locale)
          indirizzoIP = Conf.getNodeValue("Server.ip");
          if (indirizzoIP.equals("")){
        	  indirizzoIP = java.net.InetAddress.getLocalHost().getHostAddress();
          }
          
          ss = new ServerSocket(Conf.getServerPort(),100, InetAddress.getByName(indirizzoIP));
          
         
          
    	obsServerStarted(true);
    	
    	
          while(true){  
        	  
        	  
    		// PULIZIA DELLA MEMORIA
        	  System.gc();
        	  
        	  
            socket = ss.accept();
    				if (!Conf.isBanned(socket) && probes.size() < maxConnections) { 
    	        
    					// CONTROLLO LIMITE SESSIONE
    					if (sessionNr >= 2147483647){
    						sessionNr = 0;
    					}
    
    					
    			Probe p = new Probe(socket, this, sessionNr++);
    	        probes.add(p);
    					obsClientConnected(p.ses.us);
    	        p.start();
    					Conf.setSession(sessionNr);
    				}else {
    					socket.close();
    				}
          }
        }catch(SocketException se) {
    			if (!suspended){
    				obsServerStarted(false); //server could not be started
    			
    				// SERVER NON AVVIATO
    				arrestaProgramma(indirizzoIP, Conf.getServerPort() );
    
    			}
    			
        }catch(IOException e){
          bb.dockException(e,"");
    
        	
    	} catch (Exception e) {
    
    		// SERVER NON AVVIATO
    		if(indirizzoIP.equals("")){
    			indirizzoIP = "unknown";
    		}
    		arrestaProgramma(indirizzoIP, Conf.getServerPort() );
    	}
    	
    	
    	
    		if(suspended)
    			obsServerStoped();
      }
    	
    	public static void userLogedOut(Session ses) {
    		/*
    		String key = ses.getLogin() + ses.clientCommandSocket.getInetAddress().getHostAddress();
    		int i = Integer.parseInt(users.get(key).toString());
    		users.put(key,""+(--i));	
    		*/
    	}
    	
    	public void disconnect(Probe p) {
    		String login = p.ses.getLogin();
    		if (p.ses.logedIn && !login.equals("")) {
    			p.ses.logFile.stop();
    			userLogedOut(p.ses);
    			
    		}
    		
    
    		probes.remove(p);
    
    		
    		//Opdaterer observers
    		obsClientDisconnected(p.ses.us);
    		
    		//if (autoSave)
    			//Conf.save();
    
    		
    	}
    	
    	public static boolean canUserLogin(Session ses) {			
    
    		String key = ses.getLogin() + ses.clientCommandSocket.getInetAddress().getHostAddress();
    		Object o = users.get(key);
    		int now;
    		if (o == null) {
    			now = 0;
    		}else {
    			now = Integer.parseInt(o.toString());
    		}
    
    		String mls = Conf.getUserOption(ses.xml,"max_logins_per_user");
    		int mli=-1;
    		if (!mls.equals("")) {
    			try {
    				mli=Integer.parseInt(mls);
    			}catch(NumberFormatException nfe) {
    				ses.bb.commandoException(nfe, "The value ["+mls+"] i max_logins at the user: " + ses.getLogin() + " were not a number. no limits is set.");
    			}
    		}
    		
    		if (mli > now || mli < 0) {
    			users.put(key, ""+(++now));
    			return true;
    		}else
    			return false;
    
    	}
    	
    	public HashSet getUsers() {
    		return probes;
    	}
    	
    	public synchronized int getServerPort() {
    		if (ss==null) {
    			return Conf.getServerPort();
    		}else {
    			return ss.getLocalPort();
    		}
    	}
    	
    	private void obsClientConnected(UserSession us) {
    		Iterator i = obs.iterator();
    		while (i.hasNext()) {
    			((ServerObserver)i.next()).clientConnected(us);
    		}	
    	}
    	
    	private void obsClientDisconnected(UserSession us) {
    		Iterator i = obs.iterator();
    		while (i.hasNext()) {
    			((ServerObserver)i.next()).clientDisconnected(us);
    		}	
    	}
    	
    	private void obsServerStarted(boolean startOk) {
    		Iterator i = obs.iterator();
    		while (i.hasNext()) {
    			((ServerObserver)i.next()).serverStarted(startOk);
    		}	
    	}
    	
    	private void obsServerStoped() {
    		Iterator i = obs.iterator();
    		while (i.hasNext()) {
    			((ServerObserver)i.next()).serverStoped();
    		}	
    	}
    	
    	
    	
    	
    	
    	
    	
    	
    	
    	/**
    	 * FUNZIONE PER IL BLOCCO DEL PROGRAMMA E AVVISO TRAMITE MAIL
    	 *
    	 */
    	private void arrestaProgramma(String indirizzo, int porta) {
    		
    		Conf conf = Conf.getInstance();
    		
    		// INIZIALIZZO VARIABILI
    		String mail_from = "";
    		String mail_to = "";
    		String mail_tentativi_s = "3";
    		String mail_wait_time_s = "60000";
    		int mail_tentativi = 3;
    		long mail_wait_time = 300000;
    		
    		// CARICO DA CONFIGURAZIONE LE VARIABILI x INVIO MAIL
    		try{
    			
    			mail_from = conf.getNodeValue("Mail_Err.mail_from");
    			mail_to = conf.getNodeValue("Mail_Err.mail_to");
    			mail_tentativi_s = conf.getNodeValue("Mail_Err.mail_tentativi");
    			mail_wait_time_s = conf.getNodeValue("Mail_Err.mail_wait_time");
    
    		} catch (Exception e) {
    
    		}
    		
    		// CONTROLLI CAMPI E CORREZIONI
    		try{
    			
    			mail_tentativi = Integer.parseInt(mail_tentativi_s);
    			mail_wait_time = Long.parseLong(mail_wait_time_s);
    
    		} catch (Exception e) {
    
    		}
    
    		int esecuzioneProcedura = mail_tentativi;
    		
    		// CONTROLLO SE NON HO UTENTI VALIDI IMPOSTO DEFAULT
    		if(mail_from.equalsIgnoreCase("")){
    			mail_from = "network.management@vegaspa.it";
    		}
    		if(mail_to.equalsIgnoreCase("")){
    			mail_to = "network.management@vegaspa.it";
    		}
    
    		MailHelper mailHelper = new MailHelper(mail_from);
    		boolean mailInviata = false;
    		
    		// CICLO INFINITO PER INVIO MAIL
    		while (esecuzioneProcedura > 0){
    			
    			// MAIL AMMINISTRATORE AVVISO ERRORE
    			
    			String oggettoMail = "ERRORE AVVIO SERVER FTP-MQ";
    			String testoMail = "Non è stato possibile avviare il server Ftp-MQ :\n\r";
    			testoMail = testoMail + "IP : " + indirizzo + "\nPORTA : " + porta;
    			
    			mailInviata = mailHelper.sendMail(mail_to, oggettoMail, testoMail );
    			if (mailInviata==true){
    				// USCITA DAL CICLO
    				esecuzioneProcedura = 0;
    				// CHIUSURA DEL PROGRAMMA !!!
    				System.exit(-1);
    			}
    			// MAIL AMMINISTRATORE AVVISO ERRORE
    			
    			// PULIZIA DELLA MEMORIA
    			System.gc();
    			
    			// INTERVALLO DI TEMPO (default 5 minuti)
    			try {
    			  Thread.sleep(mail_wait_time);
    			}
    			catch (Exception e) {}
    			
    			// INCREMENTO IL TENTATIVO DI INVIO MAIL
    			esecuzioneProcedura = esecuzioneProcedura + 1;
    			
    		} // FINE CICLO WHILE
    		
    		// CHIUSURA DEL PROGRAMMA !!!
    		System.exit(-1);
    		
    	}
    
    	
    }
    odio chi parla di politica..
    anzi vorrei fondare un partito contro tutto ciò

  2. #2
    Utente di HTML.it L'avatar di floyd
    Registrato dal
    Apr 2001
    Messaggi
    3,837
    300k sono un'esagerazione VVoVe:
    non ho letto il codice ma una cosa veloce puoi provarla: metti un System.gc() dopo la chiusura della connessione

  3. #3
    Utente di HTML.it L'avatar di morphy79
    Registrato dal
    Jun 2004
    Messaggi
    1,568
    mi sa che non son 300k...

    adesso ho aggiunto nel metodo start questo codice...

    codice:
      public void start(){
        suspended=false;
    	th = new Thread(this);
        th.start();
    
        final Runtime rt = Runtime.getRuntime();
        Thread memoryMonitor = new Thread() {
          public void run() {
            while (true) {
               System.gc();
               System.out.println(rt.freeMemory() / 1024f);
               try { Thread.currentThread().sleep(1000); } catch (Exception ex) {}
            }
          }
        };
        memoryMonitor.start();
    
      }

    e questo è ciò che vedo a video facendo una prova di connessione:

    3685.5312
    3893.6875
    3953.0312
    4041.8125
    4041.8281
    4042.0625
    4042.0625
    4042.0625
    NEW THREAD
    4012.5312
    4101.0234
    4101.992
    4165.883
    4217.789
    4216.4844
    4209.289
    4221.1562
    4220.9766
    4232.9766
    END THREAD
    4178.3203
    4257.5312
    4257.5312
    4257.5312
    4257.5312


    ma com'è che aumenta ????
    il metodo freeMemory() non mostra la memoria libera ????


    la System.gc(); l'avevo già messa...

    odio chi parla di politica..
    anzi vorrei fondare un partito contro tutto ciò

  4. #4
    Utente di HTML.it L'avatar di floyd
    Registrato dal
    Apr 2001
    Messaggi
    3,837
    freeMemory ritorna la quantità di memoria libera
    ma ricorda che siamo in java, ovvero in una virtual machine
    la quale ha una quantità di memoria assegnata che può variare durante l'esecuzione
    esempio
    jvm mem assegnata 1000k mem occupata 500k
    jvm mem assegnata 1500k mem occupata 700k
    freeMemory ritorna due valori che sembrano crescere ma in realtà è cresciuta tutta le memoria

  5. #5
    Utente di HTML.it L'avatar di morphy79
    Registrato dal
    Jun 2004
    Messaggi
    1,568
    non c'è un modo per uccidere a mano un thread ????
    voglio che quando si chiude deve scomparire tutto... come se non fosse mai esistito...
    odio chi parla di politica..
    anzi vorrei fondare un partito contro tutto ciò

  6. #6
    Non sono pratico di Java ma direi che c'è un memory leak da qualche parte (il garbage collector non elimina un determinato oggetto).
    Per debuggare un simile problema in python esiste gc.collect() e metodi di gc derivati.
    In Java come ti ci interfacci al garbage collector? Tramite "System.gc()"? Usa quello.
    Certo che se in Java per ogni nonnulla si utilizzano i thread non mi meraviglio che accadano spesso casini difficili da debuggare, imho...
    Rilasciata Python FTP Server library 0.5.1
    http://code.google.com/p/pyftpdlib/

    We'll be those who'll make the italian folks know how difficult can be defecating in Southern California without having the crap flying all around the house.

  7. #7
    Utente di HTML.it L'avatar di morphy79
    Registrato dal
    Jun 2004
    Messaggi
    1,568
    si uso il System.gc()...
    ma non cambia molto... tra l'altro non si capisce molto bene.. monitorando la memoria varia sempre... da task manager meglio non parlarne del tutto..
    son davvero in difficoltà.. (e preoccupato mannaggia)..

    esiste un qualche un progrmma per monitorare la memoria java utilizzata ????
    odio chi parla di politica..
    anzi vorrei fondare un partito contro tutto ciò

  8. #8
    Provo a dare una risposta, anche se non conosco Java: in Java esistono dei metodi "builtin" che vengono richiamati in automatico in determinate situazioni?
    Cerco di spiegarmi meglio:
    in python esiste un metodo speciale denominato __del__ (il distruttore) che viene richiamato quando la classe 'muore', viene cioè eliminata dopo che ha svolto il suo compito.
    Il memory leak può avvenire proprio quando per qualche motivo il distruttore della classe non viene richiamato.
    Se in python fai una cosa del tipo:

    codice:
    class test:
        def __init__(self):
            ...
    
        def __del__(self):
            print "__del__"
    
    test()
    ...ti accorgi che la classe viene eliminata dal garbage collector quando la print stampa a video "__del__" (e questo, ovviamente avviene).
    In python questo può non avvenire nel caso in cui si vengano a creare dei "riferimenti circolari". Lo stesso ipotizzo accada in Java.
    Il consiglio che ti do, quindi, è quello di inserire delle 'print' in ogni metodo distruttore di ogni classe del tuo programma per renderti conto quale di esse non viene eliminata dal gc.
    Tutto questo discorso ovviamente vale solamente se Java ti permette di fare una cosa del genere (cosa di cui io non ho la minima idea).

    Se

    My 2 cents
    Rilasciata Python FTP Server library 0.5.1
    http://code.google.com/p/pyftpdlib/

    We'll be those who'll make the italian folks know how difficult can be defecating in Southern California without having the crap flying all around the house.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.