########################################################################
# $Header: /var/local/cvsroot/4Suite/Ft/Server/Server/Commands/Status.py,v 1.1 2004/10/07 08:30:00 mbrown Exp $
"""
4Suite repository status command (4ss_manager status)

Copyright 2004 Fourthought, Inc. (USA).
Detailed license and copyright information: http://4suite.org/COPYRIGHT
Project home, documentation, distributions: http://4suite.org/
"""

__doc__ = """This command lists the status of each server in a 4Suite \
repository (running or stopped) as well as the state of the repository \
itself (data store existence and initialization status)."""

import sys, os

from Ft.Server import FTSERVER_NAMESPACE
from Ft.Server.Common import ResourceTypes, Schema
from Ft.Server.Server import Drivers
from Ft.Server.Server.Commands.CommandUtil import GetRepository
from Ft.Server.Server.Lib import ConfigFile, LogUtil


def Run(options, args):

    sys.stderr.write('Repository status\n=================\n')

    #Read the config file
    # same code as in the Init command
    properties = ConfigFile.Read(options.get('config-file'))
    coreId = options.get('core-id',os.environ.get('FTSS_CORE_ID', 'Core'))
    try:
        properties = properties[coreId]
    except KeyError:
        raise FtServerServerException(Error.CONFIG_INVALID_CORE_ID, name=coreId)
    properties['CoreId'] = coreId
    driver = Drivers.Begin(LogUtil.NullLogger(), properties)
    exists = driver.exists()

    if exists == -1:
        sys.stderr.write('NO REPOSITORY: ')
        sys.stderr.write('There does not appear to be a data store.\n')
        return
    elif exists == 0:
        sys.stderr.write('UNINITIALIZED REPOSITORY: ')
        sys.stderr.write('A data store exists, but is not fully initialized.\n')
        return
    else:
        sys.stderr.write('INITIALIZED REPOSITORY: ')
        sys.stderr.write('A data store exists and appears to be initialized.\n')

    if not (options.has_key('username') and options.has_key('password')):
        sys.stderr.write('\nPlease provide authentication credentials for the repository\n')
        sys.stderr.write('in order to check the status of its servers.\n')
        sys.stderr.flush()

    username, password, properties, repo = GetRepository(options,
                                                         '4ss_manager.status')

    model = repo.getModel()
    pred = Schema.TYPE
    obj = Schema.g_rdfResourceTypes[ResourceTypes.ResourceType.SERVER]
    all_server_statements = model.complete(None, pred, obj)

    sys.stderr.write('\nScheduled status of servers in the repository\n')
    sys.stderr.write('=============================================\n')
    sys.stderr.write('status    port   server path\n-------   ----   -----------\n')
    for statement in all_server_statements:
        server_path = statement.subject
        server_obj = repo.fetchResource(server_path)
        if server_obj.resourceType != ResourceTypes.ResourceType.SERVER:
            continue

        status = server_obj.getStatus()
        server_doc = server_obj.asDom()
        port = server_doc.xpath('number(/ftss:Server/ftss:Port)',
                                explicitNss={'ftss': FTSERVER_NAMESPACE})
        sys.stderr.write('%s   %4d   %s\n' % (status and 'running' or 'stopped',
                                             port, server_path))
        sys.stderr.flush()

    repo.txRollback()

    return


def Register():
    from Ft.Lib.CommandLine import Command, Options

    cmd = Command.Command('status',
                          "Report on the state of a repository and its servers",
                          '',
                          __doc__,
                          function=Run,
                          fileName=__file__,
                          )
    return cmd

