// GridConfigApplicationFactory.java

/**
*    Copyright (C) 2008 10gen Inc.
*  
*    This program is free software: you can redistribute it and/or  modify
*    it under the terms of the GNU Affero General Public License, version 3,
*    as published by the Free Software Foundation.
*  
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU Affero General Public License for more details.
*  
*    You should have received a copy of the GNU Affero General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package ed.manager;

import java.io.*;
import java.util.*;

import ed.js.*;
import ed.db.*;
import ed.log.*;
import ed.util.*;
import ed.cloud.*;

public class GridConfigApplicationFactory extends ConfigurableApplicationFactory {

    GridConfigApplicationFactory(){
        super( Cloud.CLOUD_REFRESH_RATE );

        _cloud = Cloud.getInstanceIfOnGrid();
        if ( _cloud == null )
            throw new RuntimeException( "can't get cloud" );

        _db = _cloud.getDB();
        _serverName = _cloud.getServerName();
    }
    
    protected SimpleConfig getConfig()
        throws IOException {
        
        TextSimpleConfig config = new TextSimpleConfig();
        _addDefaultsIfAny( config );
        
        try {
            _doDBs( config );
            _doAppServers( config );
        }
        catch ( Exception e ){
            _logger.error( "couldn't load config from grid" , e );
            
            if ( _lastConfig != null ){
                _logger.info( "falling back to last config" );
                return _lastConfig;
            }
            
            if ( _cacheFile.exists() ){
                _logger.info( "have old cache file [" + _cacheFile + "] using that" );
                return TextSimpleConfig.read( _cacheFile );
            }
            
            if ( config.getTypes().size() == 0 )
                throw new RuntimeException( "can't load config from grid or cache file [" + _cacheFile + "], and no defaults, so can't do anything" );
        }
        
    
        _lastConfig = config;
        return config;
    }
    
    void _doDBs( SimpleConfig config ){ 
        for ( Iterator<JSObject> i = _db.getCollection( "dbs" ).find(); i.hasNext(); ){
            final JSObject db = i.next();
            final String name = db.get( "name" ).toString();
            
            if ( _cloud.isMyServerName( db.get( "machine" ).toString() ) ){
                config.addEntry( "db" , name , "ACTIVE" , "true" );
                config.addEntry( "db" , name , "master" , "true" );
            }
        }
        
    }

    void _doAppServers( SimpleConfig config ){ 
        for ( Iterator<JSObject> i = _db.getCollection( "pools" ).find(); i.hasNext(); ){
            final JSObject pool = i.next();
            final String name = pool.get( "name" ).toString();
            
            for ( Object machine : (List)(pool.get( "machines" )) ){
                if ( ! _cloud.isMyServerName( machine.toString() ) )
                    continue;
                
                config.addEntry( "appserver" , name , "ACTIVE" , "true" );
                return; // only 1 appserver per machine
            }
        }
    }

    void _addDefaultsIfAny( SimpleConfig config ){

        if ( JSInternalFunctions.JS_evalToBool( _cloud.getMe().get( "isGridServer" ) ) ){
            config.addEntry( "db" , "grid" , "ACTIVE" , "true" );
            config.addEntry( "db" , "grid" , "master" , "true" );
            config.addEntry( "db" , "grid" , "port" , String.valueOf( _cloud.getGridDBPort() ) );
            config.addEntry( "db" , "grid" , "dbpath" , "/data/db-grid/" );
        }
    }

    final Cloud _cloud;
    final DBBase _db;
    final String _serverName;

    private SimpleConfig _lastConfig;

    private static File _cacheFile = new File( "logs/gridappcache" );
    private static Logger _logger = Logger.getLogger( "gridappconfig" );
    
    public static void main( String args[] )
        throws Exception {
        
        System.out.println( (new GridConfigApplicationFactory()).getConfig() );

    }
}

@@ -1493,32 +1493,72 @@
 vers( config );%0A
+            _doLoadBalancers( config );%0A
         %7D%0A      
@@ -3424,32 +3424,474 @@
        %7D%0A    %7D%0A%0A
+    void _doLoadBalancers( SimpleConfig config )%7B %0A        for ( Iterator%3CJSObject%3E i = _db.getCollection( %22lbs%22 ).find(); i.hasNext(); )%7B%0A            final JSObject lb = i.next();%0A            final String machine = lb.get( %22machine%22 ).toString();%0A            %0A            if ( ! _cloud.isMyServerName( machine ) )%0A                continue;%0A                %0A            config.addEntry( %22lb%22 , machine , %22ACTIVE%22 , %22true%22 );%0A        %7D%0A    %7D%0A%0A
     void _addDef

load balancers automatic