RioShell Class Reference

#include <RioShell.h>

Inherits RioExplorer.

Public Member Functions

 RioShell (char *, char *, char *=NULL)
 ~RioShell ()
int exec (bool, bool, char *, bool)
bool connect (void)
bool showMessage (int, string, string="")
void handle_SIGINT (void)

Private Member Functions

int parsePath (char *, char *, char *=NULL)
int execCMD (CMParser *)
bool resolvePathSession (CRioSession **, char *, int *, CMParser *=NULL, unsigned int *=NULL)
 resolvePathSession analisa o nome ObjectName, verifica se se refere a uma sessão atual(*newSession recebe o session da RioExplorer), se não se refere a nenhuma sessão(*newSession recebe NULL) ou se se refere a uma sessão remota.
void clear (void)
void help (void)
void printLsInfo (vector< ObjectInfo > *, bool, bool, bool, bool, bool, unsigned int)
void printDfInfo (vector< DfInfo > *, bool, bool)
void printDuInfo (vector< DuInfo > *, bool, bool)
void printSessionsInfo (SessionsInfo *)
void printDisplayInfo (DisplayInfo *, int, bool)
void updateCopyProgress (void)
void setMD5Calculation (char *, bool)
void setSyncCheck (char *, bool)
int SearchLogs (char *SearchOptionName, char *MachineName, char *StrStartTime, char *StrEndTime, char *ResultFileName)
 Funcao usada para executar o novo comando searchlogs que faz buscas nos logs dos servidores.

Static Private Member Functions

static void SearchLogsCallback (void *param, int result)
 Funcao de callback usada quando uma busca nos logs terminar a sua execucao para desbloquear o shell.

Private Attributes

string current_file
RioObjectSize current_file_completed
RioObjectSize current_file_size
char * MachineName
char * UserName
char * Password
bool copy_allowed
bool UseVideoRate
int SearchLogsResult
CSemaphoreSearchLogsSemaphore
struct {
   char *   host
   char *   user
   char *   password
lastRemoteAccess

Static Private Attributes

static const int UPDATE_INTERVAL = 50000
static const int PROGRESS_BAR_WIDTH = 25

Detailed Description

Definition at line 45 of file RioShell.h.


Constructor & Destructor Documentation

RioShell::RioShell ( char *  MachineName,
char *  UserName,
char *  Passwd = NULL 
)

Definition at line 43 of file RioShell.cpp.

00044 {
00045     this->UserName    = UserName;
00046     this->MachineName = MachineName;
00047     this->Password    = Passwd;
00048 
00049     // Initialize lastRemoteAccess data
00050     lastRemoteAccess.host     = new char[ MAXNAMELEN ];
00051     lastRemoteAccess.user     = new char[ MAXNAMELEN ];
00052     lastRemoteAccess.password = new char[ MAXNAMELEN ];
00053 
00054     lastRemoteAccess.host[ 0 ]     = '\0';
00055     lastRemoteAccess.user[ 0 ]     = '\0';
00056     lastRemoteAccess.password[ 0 ] = '\0';
00057 
00058     copy_allowed = false;
00059     
00060     // Inicializa a variavel que diz se devemos mostrar a taxa de transmissao
00061     // do video.
00062     UseVideoRate = false;
00063     
00064     // Inicializa o semaforo usado pela busca nos logs.
00065     SearchLogsSemaphore = new CSemaphore( 0, 1 );
00066 }

RioShell::~RioShell (  ) 

Definition at line 68 of file RioShell.cpp.

00069 {
00070     // Remove o semaforo usado pela busca nos logs.
00071     delete SearchLogsSemaphore;
00072 }


Member Function Documentation

void RioShell::clear ( void   )  [private]

Definition at line 1255 of file RioShell.cpp.

01256 {
01257     int erro, errolib;
01258     erro = system( "clear" );
01259     errolib = errno;
01260     
01261     if( ( erro == -1 ) && ( errolib != ECHILD ) )
01262     {
01263         RioErr << "RioShell::clear system falhou em executar o comando clear "
01264                << " e gerou o erro " << errolib << " (" << strerror( errolib ) 
01265                << ")." << endl;
01266     }
01267     else if( ( WIFEXITED( erro ) ) && ( WEXITSTATUS( erro ) != 0 ) )
01268     {
01269         RioErr << "RioShell::clear o comando clear executou corretamente, " 
01270                << " mas retornou um valor " << WEXITSTATUS( erro ) 
01271                << " diferente de 0." << endl;
01272     }
01273     
01274 }

bool RioShell::connect ( void   ) 

Definition at line 190 of file RioShell.cpp.

00191 {
00192     // check parameter, if not sufficient, ask the user
00193     if( MachineName == NULL )
00194     {
00195         //ask user the Machine name
00196         cout << "Digite o nome do servidor RIO: ";
00197         MachineName = new char[ MAXNAMELEN ];
00198         if( fgets( MachineName, MAXNAMELEN, stdin ) == NULL )
00199         {
00200             RioErr << "RioShell::connect erro ao ler dados de stdin "
00201                    << endl;
00202         }
00203         // Remove "newline" from input string
00204         MachineName[ strlen( MachineName ) - 1 ] = 0;
00205     }
00206 
00207     if( UserName == NULL )
00208     {
00209         cout << "Digite o nome de usuário: ";
00210         UserName = new char[ MAXNAMELEN ];
00211         if ( fgets( UserName, MAXNAMELEN, stdin ) == NULL )
00212         {
00213             RioErr << "RioShell::connect erro ao ler dados de stdin "
00214                    << endl;
00215         }
00216         // Remove "newline" from input string
00217         UserName[ strlen( UserName ) - 1 ] = 0;
00218     }
00219 
00220     if( Password == NULL )
00221     {
00222         Password = new char[ MAXNAMELEN ];
00223         if( strcmp( UserName, DEFAULTUSER ) != 0 )
00224         {
00225             // Armazena a senha nao encriptada.
00226             char *UncryptedPassword;
00227 
00228             cout << "Digite a senha: ";
00229             UncryptedPassword = getpass( "" );
00230             if( strlen( UncryptedPassword ) > MAXPASSWORDSIZE )
00231             {
00232                 RioErr << "RioShell::password is too long!"  << endl;
00233                 return false;
00234             }
00235 
00236             Password = encryptPassword( UncryptedPassword );
00237         }
00238         else
00239             Password = encryptPassword( DEFAULTUSER );
00240     }
00241     else
00242         Password = encryptPassword( Password );
00243 
00244 
00245     // Connect to server
00246     session = createSession( MachineName, UserName, Password );
00247 
00248     if( session != NULL )
00249     {
00250         string message;
00251         int result;
00252         // Novo codigo, usado pela implementacao de controle de fluxo,
00253         // para verificar se o servidor possui o controle de fluxo e, em caso 
00254         // afirmativo, criar o item no objeto fileList e inicializar o campo
00255         // UseVideoRate. Isso precisa ser feito nesta funcao (ao inves do 
00256         // construtor) porque precisamos de uma sessao ativa para chamar o 
00257         // metodo que verifica se o servidor possui ou nao o controle de fluxo.
00258         result = session->CheckStreamControl( &UseVideoRate );
00259         if( FAILED( result ) ) {
00260             message = "Could not check stream control implementation.\n";
00261             showMessage( ERROR_MSG, message );
00262             UseVideoRate = false;
00263         } 
00264         return true;
00265     }
00266     else
00267         return false;
00268 }

int RioShell::exec ( bool  commandMode,
bool  stdOut,
char *  cmdLine1,
bool  pipeMode 
)

Definition at line 74 of file RioShell.cpp.

00076 {
00077     string         message;
00078     char          *cmdLine = NULL;
00079     char           rioPrompt[ 128 ];
00080 
00081     string         history_filename;
00082     HISTORY_STATE *current_history_state;
00083     int            n_cmds;
00084     int            result = 0;
00085 
00086     session->GetCurrentDir( HomeDir, MAXNAMELEN );
00087 
00088     /* reading last saved history */
00089     using_history( );
00090     if( getenv( "HOME" ) != NULL )
00091     {
00092         history_filename = getenv( "HOME" );
00093         history_filename += "/.riosh_history";
00094     }
00095     else
00096         history_filename = "/dev/null";
00097 
00098     if( read_history( history_filename.c_str( ) ) != 0 )
00099     {
00100         if( errno == ENOENT )
00101             write_history( history_filename.c_str( ) );
00102         else
00103             Rioperror( "error reading history" );
00104     }
00105 
00106     /* rio shell command line processing loop */
00107     while( true )
00108     {
00109         cmdLine = NULL;
00110         if( !commandMode )
00111         {
00112             session->GetCurrentDir( curDir, MAXNAMELEN );
00113             sprintf( rioPrompt, "riosh:%s> ", curDir );
00114 
00115             if( !stdOut )
00116                 // the line returned has no newline
00117                 cmdLine = readline( rioPrompt );
00118             else
00119                 /* if stdOut == true the prompt is omitted */
00120                 cmdLine = readline( NULL ); // the line returned has no newline
00121         }
00122         else
00123            cmdLine = cmdLine1;
00124 
00125         if( cmdLine == NULL ) //cmdLine will only be NULL if readline gets an
00126                               //EOF - which only occurs in pipe mode
00127                               //riosh is allowed to stop parsing without error
00128         {
00129             showMessage( INFO_MSG, "\n" );
00130             break;
00131         }
00132 
00133         if( strlen( cmdLine ) == 0 )
00134         {
00135             continue;
00136         }
00137         else
00138             add_history( cmdLine );
00139 
00140         CMParser *cm = new CMParser( cmdLine );
00141 
00142         if( cm->GetCMD() == EXIT )
00143         {
00144             break;
00145         }
00146 
00147         if( cm->GetCMD() == INVCMD )
00148         {
00149             message  = "Comando inválido. Tente \"ajuda\" or \"?\" para ";
00150             message += "visualizar comandos disponíveis.\n";
00151             showMessage( ERROR_MSG, message );
00152             if( !commandMode && !pipeMode )
00153             {
00154                 continue;
00155             }
00156             else
00157             {
00158                 result = RIOSHELL_ERROR;
00159                 break;
00160             }
00161         }
00162 
00163         result = execCMD( cm );
00164 
00165         if( !commandMode )
00166         {
00167             delete cm;
00168             free( cmdLine );
00169             if( pipeMode && ( result != 0 ) ) //abort if the command has failed
00170                 break;
00171         }
00172         else
00173         {
00174             //result already set
00175             break;
00176         }
00177     } // fim do while( true )
00178 
00179     /* writing current history */
00180     current_history_state = history_get_history_state();
00181     n_cmds = current_history_state->length;
00182     if( append_history( n_cmds, history_filename.c_str( ) ) )
00183         Rioperror( "error writing history" );
00184     if( history_truncate_file( history_filename.c_str( ), 1000 ) )
00185         Rioperror( "error writing history" );
00186 
00187     return result;
00188 }

int RioShell::execCMD ( CMParser cm  )  [private]

Definition at line 273 of file RioShell.cpp.

00274 {
00275     const int ObjectNameSize = MAXNAMELEN;
00276     string     message;
00277     int        error_value = ERROR_NO_RIO_ERROR;
00278 
00279     if( cm->GetOpt( '-' ) != 0 )
00280     {
00281         cm->ShowUsage();
00282     } else if( cm->GetCMD() == LS )
00283     {
00284         int  DirType;
00285         bool humanread, numberofblocks, recursive, listinfo, simplels, allFiles,
00286              showvideorate;
00287         char ObjectName[MAXNAMELEN];
00288 
00289         // Directory Name
00290         if( cm->GetParam( 0 ) != 0 )
00291             strcpy( ObjectName, cm->GetParam( 0 ) );
00292         else
00293             ObjectName[0] = '\0';
00294 
00295         // Human Read
00296         if( cm->GetOpt( 'h' ) != 0 )
00297             humanread = true;
00298         else
00299             humanread = false;
00300 
00301         // Number of Blocks
00302         if( cm->GetOpt( 'B' ) != 0 )
00303             numberofblocks = true;
00304         else
00305             numberofblocks = false;
00306 
00307         // Recursive
00308         if( cm->GetOpt( 'r' ) != 0 )
00309             recursive = true;
00310         else
00311             recursive = false;
00312 
00313         // Metadata
00314         if( cm->GetOpt( 'l' ) != 0 )
00315             listinfo = true;
00316         else
00317             listinfo = false;
00318 
00319         // Simple format
00320         if( cm->GetOpt( 's' ) != 0 )
00321             simplels = true;
00322         else
00323             simplels = false;
00324 
00325         // List all files
00326         if( cm->GetOpt( 'a' ) != 0 )
00327             allFiles = true;
00328         else
00329             allFiles = false;
00330         
00331         // Nova opcao para definir se a taxa de transmissao deve ser mostrada.    
00332         // Show video rate
00333         if( cm->GetOpt( 'e' ) != 0 )
00334             showvideorate = true;
00335         else
00336             showvideorate = false;
00337            
00338             
00339 
00340         CRioSession *lsSession  = NULL;
00341         bool         lsStatus = true;
00342 
00343         lsStatus = resolvePathSession( &lsSession, ObjectName, &DirType, cm );
00344 
00345         if( lsStatus )
00346         {
00347             vector<ObjectInfo> info;
00348             vector<ObjectInfo> infoList;
00349             vector<ObjectInfo> appendList;
00350 
00351             if( strcmp( ObjectName, "" ) == 0 )
00352                 lsStatus = ls( NULL, &infoList, lsSession, allFiles, recursive );
00353             else
00354             {
00355                 lsStatus = resolveRegExp( &info, lsSession, ObjectName );
00356                 for( unsigned int i = 0; lsStatus && ( i < (unsigned int)info.size() ); i++ )
00357                 {
00358                     appendList.clear();
00359                     lsStatus = lsStatus && ls( &info[i], &appendList, lsSession, allFiles, recursive );
00360 
00361                     if( ( info.size() > 1 ) && info[i].isDir() )
00362                     {
00363                         for( unsigned int j = 0; lsStatus && ( j < (unsigned int)appendList.size() ); j++ )
00364                         {
00365                             string newPath = appendList[j].getPath();
00366                             newPath.insert( 0, "/" );
00367                             newPath.insert( 0, info[i].getFullName() );
00368                             appendList[j].setPath( newPath );
00369                         }
00370                     }
00371 
00372                     infoList.insert( infoList.end(), appendList.begin(), appendList.end() );
00373                 }
00374             }
00375 
00376             if( lsStatus )
00377             {
00378                 if( infoList.size() > 0 )
00379                 {
00380                     unsigned int BlockSize;
00381                     getBlockSize( &BlockSize, lsSession );
00382                     // O novo parametro booleano da funcao printLsInfo diz se 
00383                     // a taxa de transmissao deve ou nao ser mostrada.
00384                     printLsInfo( &infoList, humanread, numberofblocks, listinfo,
00385                                  simplels, showvideorate, BlockSize );
00386                 }
00387                 else if( ( info.size() == 0 ) && ( strlen( ObjectName ) > 0 ) )
00388                 {
00389                     message  = "ls:  ";
00390                     message += ObjectName;
00391                     message += ": Arquivo ou diretório inexistente.\n";
00392                     showMessage( INFO_MSG, message );
00393                     error_value = RIOSHELL_ERROR;
00394                 }
00395             }
00396             else
00397             {
00398                 message  = "ls: Erro ao listar ";
00399                 message += ObjectName;
00400                 message += ".\n";
00401                 showMessage( ERROR_MSG, message );
00402                 error_value = RIOSHELL_ERROR;
00403             }
00404         }
00405 
00406         if( ( DirType == REMOTE ) && ( lsSession != NULL ) )
00407         {
00408             lsSession->Disconnect();
00409             delete lsSession;
00410         }
00411     }
00412     else if( cm->GetCMD() == DISPLAY )
00413     {
00414         char     ObjectName[ObjectNameSize];
00415         int start, size;
00416         bool     showhexadeximal;
00417 
00418         strcpy( ObjectName, cm->GetParam( 0 ) );
00419 
00420         if( cm->GetOpt( 'i' ) != 0 )
00421             start = atol( cm->GetOpt( 'i' ) );
00422         else
00423             start = 0;
00424 
00425         if( cm->GetOpt( 's' ) != 0 )
00426             size = atol( cm->GetOpt( 's' ) );
00427         else
00428             size  = 0;
00429 
00430         if( cm->GetOpt( 'h' ) != 0 )
00431             showhexadeximal = true;
00432         else
00433             showhexadeximal = false;
00434 
00435         DisplayInfo info;
00436         if( display( &info, ObjectName, start,
00437                      size, showhexadeximal ) )
00438             printDisplayInfo( &info, start, showhexadeximal );
00439         else
00440             error_value = RIOSHELL_ERROR;
00441 
00442     }
00443     else if( cm->GetCMD() == CLEAR )
00444     {
00445         clear();
00446     }
00447     else if( cm->GetCMD() == MKDIR )
00448     {
00449         int          DirType;
00450         CRioSession *mkdirSession = NULL;
00451         char         DirectoryName[MAXNAMELEN];
00452         bool         mkdirStatus  = true;
00453 
00454         // New Directory
00455         strcpy( DirectoryName, cm->GetParam( 0 ) );
00456 
00457         mkdirStatus = resolvePathSession( &mkdirSession, DirectoryName, 
00458                                           &DirType, cm );
00459 
00460         if( mkdirStatus )
00461                 error_value = (int)!(mkdir( DirectoryName, mkdirSession ));
00462     }
00463     else if( cm->GetCMD() == RM )
00464     {
00465         int          DirType;
00466         char         ObjectName[ObjectNameSize];
00467         bool         recursive, askuser;
00468         CRioSession *rmSession  = NULL;
00469         bool         rmStatus = true;
00470 
00471         //Object Name
00472         strcpy( ObjectName, cm->GetParam( 0 ) );
00473 
00474         //recursively copy
00475         if( cm->GetOpt( 'r' ) )
00476             recursive = true;
00477         else
00478             recursive = false;
00479 
00480         //ask user to confirm
00481         if( cm->GetOpt( 'f' ) )
00482             askuser = false;
00483         else
00484             askuser = true;
00485 
00486         rmStatus = resolvePathSession( &rmSession, ObjectName, &DirType, cm );
00487 
00488         if( rmStatus )
00489         {
00490             vector<ObjectInfo> rmList;
00491 
00492             rmStatus = resolveRegExp( &rmList, rmSession, ObjectName );
00493             for( unsigned int i = 0; rmStatus && ( i < (unsigned int)rmList.size() ); i++ )
00494                 rmStatus = rmStatus && rm( &rmList[i], rmSession, askuser, recursive );
00495         }
00496 
00497         if( ( DirType == REMOTE ) && ( rmSession != NULL ) )
00498         {
00499             rmSession->Disconnect();
00500             delete rmSession;
00501         }
00502         error_value = (int)!rmStatus;
00503     }
00504     else if( cm->GetCMD() == COPY )
00505     {
00506         int  SrcType;
00507         int  DestType;
00508         CRioSession *session_src  = NULL;
00509         CRioSession *session_dest = NULL;
00510         bool recursive;
00511         bool askuser;
00512         bool cpStatus = true;
00513         bool success = true;
00514         // Novo valor para indicar o numero do parametro '-p' com a senha. Este
00515         // valor sera incrementado pela funcao resolvePathSession sempre que for
00516         // necessario obter uma senha (somente quando a conexao for remota).
00517         unsigned int NextPassword;
00518 
00519         char src[MAXNAMELEN];
00520         char dest[MAXNAMELEN];
00521         
00522         // Inicializa a variavel NextPassword.
00523         NextPassword = 0;
00524 
00525         //Getting Source and Destination names
00526         strcpy( src, cm->GetParam( 0 ) );
00527         strcpy( dest, cm->GetParam( 1 ) );
00528 
00529         //Getting Source and Destination sessions
00530         cpStatus = resolvePathSession( &session_src, src, &SrcType, cm, 
00531                                        &NextPassword );
00532         cpStatus = cpStatus && resolvePathSession( &session_dest, dest, 
00533                                                    &DestType, cm, 
00534                                                    &NextPassword );
00535 
00536         // recursively copy
00537         if( cm->GetOpt( 'r' ) )
00538             recursive = true;
00539         else
00540             recursive = false;
00541 
00542         // Ask user to confirm
00543         if( cm->GetOpt( 'f' ) )
00544             askuser = false;
00545         else
00546             askuser = true;
00547 
00548         if( cpStatus )
00549         {
00550             vector<ObjectInfo> srcRegExp;
00551             cpStatus = resolveRegExp( &srcRegExp, session_src, src );
00552 
00553             if( cpStatus && ( srcRegExp.size() > 0 ) )
00554             {
00555                 if( srcRegExp.size() > 1 )
00556                 {
00557                     ObjectInfo destInfo;
00558                     if( !getObjectInfo( dest, session_dest, &destInfo, false ) ||
00559                         !destInfo.isDir()
00560                       )
00561                     {
00562                         message  = "\ncp: diretório de destino \"";
00563                         message += dest;
00564                         message += "\" não existe.\n";
00565                         showMessage( ERROR_MSG, message );
00566                         cpStatus = false;
00567                         error_value = (int)!cpStatus;
00568                     }
00569                 }
00570 
00571                 if( cpStatus )
00572                 {
00573                     copy_allowed = true;
00574 
00575                     for( unsigned int i = 0;
00576                          cpStatus && (i < srcRegExp.size());
00577                          i++ )
00578                     {
00579                         if( !cp( session_src, session_dest,
00580                                  &srcRegExp[i], dest,
00581                                  askuser, recursive, &copy_allowed,
00582                                  &current_file,
00583                                  &current_file_completed,
00584                                  &current_file_size ) )
00585                         {
00586                             if( copy_allowed )
00587                             {
00588                                 success = false;
00589                                 showMessage( ERROR_MSG,
00590                                     "\ncp: There was an error with the copy!\n" );
00591                                 error_value = RIOSHELL_ERROR;
00592                             }
00593                             break;
00594                         }
00595                     }
00596 
00597                     if( success )
00598                         showMessage( INFO_MSG, "\nCópia concluída com sucesso.\n" );
00599                 }
00600             }
00601             else
00602             {
00603                 showMessage( ERROR_MSG, "cp: File does not exist!\n" );
00604                 error_value = RIOSHELL_ERROR;
00605             }
00606         }
00607         else
00608             error_value = RIOSHELL_ERROR;
00609 
00610         // Fechando as sessoes criadas para uso no COPY
00611         if( ( SrcType == REMOTE ) && ( session_src != NULL ) )
00612         {
00613             session_src->Disconnect();
00614             delete session_src;
00615         }
00616         if( ( DestType == REMOTE ) && ( session_dest != NULL ) )
00617         {
00618             session_dest->Disconnect();
00619             delete session_dest;
00620         }
00621     }
00622 
00623     else if( cm->GetCMD() == SYNC )
00624     {
00625         int  MasterType;
00626         int  SlaveType;
00627         CRioSession *session_master  = NULL;
00628         CRioSession *session_slave = NULL;
00629         bool syncStatus = true;
00630         char master[MAXNAMELEN];
00631         char slave[MAXNAMELEN];
00632         // Novo valor para indicar o numero do parametro '-p' com a senha. Este
00633         // valor sera incrementado pela funcao resolvePathSession sempre que for
00634         // necessario obter uma senha (somente quando a conexao for remota).
00635         unsigned int NextPassword;
00636 
00637         // Inicializa a variavel NextPassword.
00638         NextPassword = 0;
00639 
00640         //Getting Master and Slave names
00641         strcpy( master, cm->GetParam( 0 ) );
00642         strcpy( slave, cm->GetParam( 1 ) );
00643         
00644         //Getting Master and Slave sessions
00645         syncStatus = resolvePathSession( &session_master, master, &MasterType,
00646                                          cm, &NextPassword );
00647         syncStatus = syncStatus && resolvePathSession( &session_slave, slave, 
00648                                                        &SlaveType, cm, 
00649                                                        &NextPassword );
00650 
00651         if( syncStatus )
00652         {
00653             vector<ObjectInfo> masterRegExp;
00654             vector<ObjectInfo> slaveRegExp;
00655             syncStatus = resolveRegExp( &masterRegExp, session_master, master );
00656             syncStatus = syncStatus && resolveRegExp( &slaveRegExp, session_slave, slave );
00657 
00658             if( syncStatus )
00659             {
00660                 syncStatus = sync( (QString) master, session_master, (QString) slave, session_slave,
00661                                      &current_file, &current_file_completed, &current_file_size );
00662             }
00663         }
00664 
00665         if( syncStatus )
00666             showMessage( INFO_MSG, "\nSincronização concluída com sucesso.\n" );
00667         else
00668         {
00669             showMessage( ERROR_MSG, "sync: ERROR!\n" );
00670             error_value = RIOSHELL_ERROR;
00671         }
00672 
00673         // Fechando as sessoes criadas para uso no SYNC
00674         if( ( MasterType == REMOTE ) && ( session_master != NULL ) )
00675         {
00676             session_master->Disconnect();
00677             delete session_master;
00678         }
00679         if( ( SlaveType == REMOTE ) && ( session_slave != NULL ) )
00680         {
00681             session_slave->Disconnect();
00682             delete session_slave;
00683         }
00684         
00685     }
00686 
00687     else if( cm->GetCMD() == CD )
00688     {
00689         char DirectoryName[MAXNAMELEN];
00690 
00691         if( cm->GetParam( 0 ) == 0 )
00692             strcpy( DirectoryName, HomeDir );
00693         else
00694             strcpy( DirectoryName, cm->GetParam( 0 ) );
00695 
00696         error_value = (int)!(cd( DirectoryName, session ));
00697     }
00698     else if( cm->GetCMD() == CREATE )
00699     {
00700         char ObjectName[ObjectNameSize];
00701         unsigned int ObjectSize;
00702 
00703         //Object size
00704         ObjectSize = atol( cm->GetParam( 1 ) );
00705 
00706         //Object name
00707         strcpy( ObjectName, cm->GetParam( 0 ) );
00708 
00709         if( createObject( ObjectName, ObjectSize ) == false )
00710         {
00711             showMessage( ERROR_MSG, "Não foi possível criar objeto.\n" );
00712             error_value = RIOSHELL_ERROR;
00713         }
00714     }
00715     else if( cm->GetCMD() == HELP )
00716     {
00717         help();
00718     }
00719     else if( cm->GetCMD() == DF )
00720     {
00721         bool humanread, numberofblocks;
00722 
00723         // Human Read
00724         if( cm->GetOpt( 'h' )!= 0 )
00725             humanread = true;
00726         else
00727             humanread = false;
00728 
00729         // Number of Blocks
00730         if( cm->GetOpt( 'B' )!= 0 )
00731             numberofblocks = true;
00732         else
00733             numberofblocks = false;
00734 
00735         vector<DfInfo> info;
00736         if( df( &info ) )
00737             printDfInfo( &info, humanread, numberofblocks );
00738         else
00739             error_value = RIOSHELL_ERROR;
00740     }
00741     else if( cm->GetCMD() == DU )
00742     {
00743         int  DirType;
00744         char ObjectName[MAXNAMELEN];
00745         bool humanread, numberofblocks, showallfiles;
00746 
00747         // Directory Name
00748         if( cm->GetParam( 0 )!= 0 )
00749             strcpy( ObjectName, cm->GetParam( 0 ) );
00750         else
00751             strcpy( ObjectName, "." );
00752 
00753         // Human Read
00754         if( cm->GetOpt( 'h' )!= 0 )
00755             humanread = true;
00756         else
00757             humanread = false;
00758 
00759         // Number of Blocks
00760         if( cm->GetOpt( 'B' )!= 0 )
00761             numberofblocks = true;
00762         else
00763             numberofblocks = false;
00764 
00765         // Show all files
00766         if( cm->GetOpt( 'a' )!= 0 )
00767             showallfiles = true;
00768         else
00769             showallfiles = false;
00770 
00771         CRioSession *duSession  = NULL;
00772         bool         duStatus = true;
00773 
00774         duStatus = resolvePathSession( &duSession, ObjectName, &DirType, cm );
00775 
00776         if( duStatus )
00777         {
00778             vector<DuInfo> info;
00779             if( du( &info, ObjectName, duSession, showallfiles ) )
00780                 printDuInfo( &info, humanread, numberofblocks );
00781             else
00782                 error_value = RIOSHELL_ERROR;
00783         }
00784         else
00785         {
00786             message  = "du: Erro ao analisar ";
00787             message += ObjectName;
00788             message += ".\n";
00789             showMessage( ERROR_MSG, message );
00790             error_value = RIOSHELL_ERROR;
00791         }
00792 
00793         if( ( DirType == REMOTE ) && ( duSession != NULL ) )
00794         {
00795             duSession->Disconnect();
00796             delete duSession;
00797         }
00798     }
00799     else if( cm->GetCMD() == SESSIONS )
00800     {
00801         SessionsInfo info;
00802         if( sessions( &info ) )
00803             printSessionsInfo( &info );
00804         else
00805             error_value = RIOSHELL_ERROR;
00806     }
00807     else if( cm->GetCMD() == MEASURES )
00808     {
00809         error_value = (int)!(measures());
00810     }
00811     else if( cm->GetCMD() == MV )
00812     {
00813         char CurrentName[MAXNAMELEN];
00814         char NewName[MAXNAMELEN];
00815         bool askuser;
00816 
00817         // Current Name
00818         strcpy( CurrentName, cm->GetParam( 0 ) );
00819 
00820         // New Name
00821         strcpy( NewName, cm->GetParam( 1 ) );
00822 
00823         //ask user to confirm
00824         if( cm->GetOpt( 'f' ) )
00825             askuser = false;
00826         else
00827             askuser = true;
00828 
00829         int          DirType;
00830         CRioSession *mvSession  = NULL;
00831         char         machineSrc[MAXNAMELEN];
00832         char         machineDest[MAXNAMELEN];
00833         char         srcName[MAXNAMELEN];
00834         char         destName[MAXNAMELEN];
00835 
00836         strcpy( srcName, CurrentName );
00837         strcpy( destName, NewName );
00838 
00839         parsePath( srcName, machineSrc );
00840         parsePath( destName, machineDest );
00841 
00842         if( ( strlen( machineSrc ) != strlen( machineDest ) ) ||
00843             ( strlen( machineSrc ) && strcmp( machineSrc, machineDest ) )
00844           )
00845         {
00846             showMessage( ERROR_MSG, "Não é permitido mover arquivos entre sessões diferentes.\n" );
00847             error_value = RIOSHELL_ERROR;
00848         }
00849         else if( ( ( strchr( CurrentName, ':' ) == NULL ) &&
00850                    ( strchr( NewName, ':') != NULL )
00851                  ) ||
00852                  ( ( strchr( CurrentName, ':' ) != NULL ) &&
00853                    ( strchr( NewName, ':') == NULL )
00854                  )
00855                )
00856         {
00857             showMessage( ERROR_MSG, "Não é permitido mover arquivos entre servidor RIO e local.\n" );
00858             error_value = RIOSHELL_ERROR;
00859         }
00860         else
00861         {
00862             if( resolvePathSession( &mvSession, CurrentName, &DirType, cm ) )
00863                 error_value = (int)!( mv( srcName, destName, mvSession, 
00864                                           askuser ) );
00865             else
00866                 error_value = RIOSHELL_ERROR;
00867         }
00868 
00869         if( ( DirType == REMOTE ) && ( mvSession != NULL ) )
00870         {
00871             mvSession->Disconnect();
00872             delete mvSession;
00873         }
00874     } else if( cm->GetCMD() == CHANGERATE ) // Novo comando usado pela 
00875                                             // implementacao do controle de
00876                                             // fluxo para alterar a taxa de
00877                                             // transmissao do video. 
00878     {
00879         if( UseVideoRate )
00880         {
00881             char ObjectName[ ObjectNameSize ];
00882             CRioStream *stream;
00883             CRioObject *object;
00884             RioResult result;
00885             unsigned int VideoRate;
00886 
00887             // Video rate
00888             VideoRate = atol( cm->GetParam( 1 ) );
00889 
00890             // Object name
00891             strcpy( ObjectName, cm->GetParam( 0 ) );
00892         
00893             // Altera a taxa de transmissao do video.
00894         
00895             stream = createNRTStream( session );
00896             if( stream == NULL )
00897             {
00898                 error_value = RIOSHELL_ERROR;
00899                 message = "Stream creation error.\n";
00900                 showMessage( ERROR_MSG, message );
00901             } 
00902             else 
00903             {
00904                 // Tentamos criar um objeto para alterar o valor da taxa de
00905                 // transmissao.
00906                 object = new CRioObject;
00907                 if( object == NULL)
00908                 {
00909                     error_value = RIOSHELL_ERROR;
00910                     message = "Object creation error.\n";
00911                     showMessage( ERROR_MSG, message );
00912                 }
00913                 else
00914                 {    
00915                     result = object->Open( ObjectName, RIO_RW_ACCESS, stream );
00916                     if( FAILED( result ) ){
00917                         error_value = RIOSHELL_ERROR;
00918                         message = "Can not open object ";
00919                         message += ObjectName;
00920                         message += ".\n";
00921                         showMessage( ERROR_MSG, message );
00922                     } 
00923                     else
00924                     {
00925                         // Tenta alterar a taxa de transmissao do video.
00926                         result = object->SetVideoRate( VideoRate );                     
00927                         if( FAILED( result ) ){
00928                             error_value = RIOSHELL_ERROR;
00929                             message = "Can not change transmission rate of ";
00930                             message += "object ";
00931                             message += ObjectName;
00932                             message += ".\n";
00933                             showMessage( ERROR_MSG, message );
00934                         }
00935                     }
00936                     delete object;
00937                 }
00938                 delete stream;                                      
00939             }
00940         } 
00941         else
00942         {
00943             error_value = RIOSHELL_ERROR;
00944             message = "Server does not support flow control.\n";
00945             showMessage( ERROR_MSG, message );
00946         }
00947     } else if( cm->GetCMD() == HELPCMD )
00948     {
00949         // Esta opcao somente e para evitar a geracao do erro dado abaixo.
00950         // Antes, o erro era gerado se um comando valido fosse usado de modo
00951         // incorreto.
00952     } else if( cm->GetCMD() == SEARCHLOGS ) // Novo comando usado para fazer 
00953                                             // buscas nos arquivos de logs.
00954     {         
00955           // Executa a funcao que trata do comando que executa a busca.
00956           error_value = SearchLogs( cm->GetParam( 0 ), cm->GetParam( 1 ),
00957                                     cm->GetParam( 2 ), cm->GetParam( 3 ),
00958                                     cm->GetParam( 4 ) );                            
00959     }                                       
00960     else
00961     {
00962         RioErr << "Unknown command" << endl;
00963         error_value = RIOSHELL_ERROR;
00964     }
00965 
00966     return error_value;
00967 }

void RioShell::handle_SIGINT ( void   ) 

Definition at line 1310 of file RioShell.cpp.

01311 {
01312     cout << endl;
01313 
01314     //Flushing readline() buffer
01315     rl_initialize();
01316 
01317     //Quiting interrupted readline()
01318     rl_free_line_state();
01319     
01320     //Interrupt copy
01321     copy_allowed = false;
01322 }

void RioShell::help ( void   )  [private]

Definition at line 1404 of file RioShell.cpp.

01405 {
01406     cout << "\nCOMANDOS DISPONÍVEIS\n"<< endl;
01407     cout << "\tls [OPÇÕES] [NOME_DO_DIRETÓRIO]" << endl;
01408     cout << "\tcd [NOME_DO_DIRETÓRIO]"  << endl;
01409     cout << "\tmkdir NOME_DO_DIRETÓRIO" << endl;
01410     cout << "\tcp [OPÇÕES] FONTE DESTINO" << endl;
01411     cout << "\tsync [DIRETORIO_MASTER] [DIRETORIO_SLAVE]" << endl;
01412     cout << "\trm [OPÇÕES] NOME_DO_OBJETO" << endl;
01413     cout << "\tchangerate NOME_DO_OBJETO NOVA_TAXA" << endl;
01414     cout << "\tcreate NOME_DO_OBJETO TAMANHO" << endl;
01415     cout << "\tcat NOME_DO_OBJETO" << endl;
01416     cout << "\tdf [OPÇÕES]" << endl;
01417     cout << "\tdu [OPÇÕES] [NOME_DO_OBJETO]" << endl;
01418     cout << "\tsessions" << endl;
01419     cout << "\tsalvarmedidas"<< endl;
01420     cout << "\tsearchlogs NOME_DO_SERVIDOR TIPO_DE BUSCA TEMPO_INICIAL ";
01421     cout << "TEMPO_FINAL ARQUIVO_RESULTADO" << endl;
01422     cout << "\tclear"<< endl;
01423     cout << "\tajuda"<< endl;
01424     cout << "\t?"<< endl;
01425     cout << "\tsair" << endl;
01426     cout << "\tquit" << endl;
01427     cout << "\texit" << endl;
01428     cout << "\n\tPara maiores informações sobre cada comando, digite 'nome_do_comando --ajuda' ";
01429     cout << endl << endl;
01430 }

int RioShell::parsePath ( char *  path,
char *  machine,
char *  user = NULL 
) [private]

Definition at line 1336 of file RioShell.cpp.

01337 {
01338     string  message;
01339     int     Type;
01340     char   *pos;
01341 
01342     //The source file is at Linux file system
01343     if( path[0] == ':' )
01344     {
01345         Type = LOCAL;
01346 
01347         strcpy( path, path + 1 );
01348         machine[0] = '\0';
01349 
01350         // Inicializa o campo com o nome do usuario com a string vazia, pois
01351         // esta conexao nao e remota.
01352         if( user != NULL )
01353             user[0] = '\0';
01354     }
01355     //The source file is at another RIO server
01356     else if( ( pos = strchr( path, ':' ) ) != 0 )
01357     {
01358         Type = REMOTE;
01359 
01360         *pos = '\0';
01361         
01362         // Inicialmente divide o campo na parte relacionada ao servidor e ao
01363         // diretorio.
01364         strcpy( machine, path );
01365         strcpy( path, pos + 1 );
01366         // Verifica se um usuario foi passado.
01367         if( ( pos = strchr( machine, '@' ) ) != 0 )
01368         {
01369             // Divide o campo machine na maquina e no nome do usuario.
01370             *pos = '\0';
01371             if( user != NULL )
01372             {
01373                 // Note que se user for NULL, o nome do usuario sera ignorado.
01374                 strcpy( user, machine );
01375             }
01376             strcpy( machine, pos + 1 );
01377         }
01378         else 
01379         {
01380           // Um usuario nao foi passado. Entao, devemos retornar a string vazia.
01381           if( user != NULL )
01382               user[0] = '\0';
01383         }
01384     }
01385     //The source file is at RIO server
01386     else
01387     {
01388         Type = SERVER;
01389 
01390         machine[0] = '\0';
01391 
01392         // Inicializa o campo com o nome do usuario com a string vazia, pois
01393         // esta conexao nao e remota.
01394         if( user != NULL )
01395             user[0] = '\0';
01396 
01397         if( strcmp( path, "." ) == 0 )
01398             strcpy( path, curDir );
01399     }
01400 
01401     return Type;
01402 }

void RioShell::printDfInfo ( vector< DfInfo > *  info,
bool  humanread,
bool  numberofblocks 
) [private]

Definition at line 1014 of file RioShell.cpp.

01016 {
01017     char aux[256];
01018     string message;
01019 
01020     message = "Máquina         | Dispositivo          | Tamanho";
01021     if( humanread )
01022         message += "    | Em uso     | Disponível  ";
01023     else
01024         message += "           | Em uso            | Disponível         ";
01025     if( numberofblocks )
01026         message += "| Total de blocos | Blocos Disponíveis  ";
01027     message += "| Em uso %\n";
01028 
01029     for( unsigned int i = 0; i < info->size() ; i++ )
01030     {
01031         for( unsigned int j = 0; j < (*info)[i].storage_df_info.size(); j++ )
01032         {
01033             sprintf( aux, "%-15s | %-20s | ",
01034                      (*info)[i].storage_df_info[j].hostname.c_str(),
01035                      (*info)[i].storage_df_info[j].diskname.c_str() );
01036             message += aux;
01037             if( humanread )
01038             {
01039                 sprintf( aux, "%10s | %10s | %10s  ",
01040                 formatSize( (*info)[i].storage_df_info[j].size ).c_str(),
01041                 formatSize( (*info)[i].storage_df_info[j].used_size ).c_str(),
01042                 formatSize( (*info)[i].storage_df_info[j].free_size ).c_str() );
01043                 message += aux;
01044             }
01045             else
01046             {
01047                 sprintf( aux, "%17llu | %17llu | %17llu  ",
01048                          (*info)[i].storage_df_info[j].size,
01049                          (*info)[i].storage_df_info[j].used_size,
01050                          (*info)[i].storage_df_info[j].free_size );
01051                 message += aux;
01052             }
01053 
01054             if( numberofblocks )
01055             {
01056                 sprintf( aux, "| %15u | %18u  ",
01057                          (*info)[i].storage_df_info[j].total_blocks,
01058                          (*info)[i].storage_df_info[j].free_blocks );
01059                 message += aux;
01060             }
01061             sprintf( aux, "| %3.1f%%\n",
01062             ( ( (*info)[i].storage_df_info[j].used_blocks * 100.0 )
01063                 / (*info)[i].storage_df_info[j].total_blocks ) );
01064             message += aux;
01065         }
01066 
01067         message += "----------------|----------------------|-";
01068         if( humanread )
01069             message += "-----------|------------|-------------";
01070         else
01071             message += "------------------|-------------------|--------------------";
01072         if( numberofblocks )
01073             message += "|-----------------|---------------------";
01074         message += "|-------\n";
01075 
01076         message +=  "                                 Total | ";
01077 
01078         if( humanread )
01079         {
01080             sprintf( aux, "%10s | %10s | %10s  ",
01081                       formatSize( (*info)[i].used_size +
01082                                   (*info)[i].free_size ).c_str(),
01083                       formatSize( (*info)[i].used_size ).c_str(),
01084                       formatSize( (*info)[i].free_size ).c_str() );
01085             message += aux;
01086         }
01087         else
01088         {
01089             sprintf( aux, "%17llu | %17llu | %17llu  ",
01090                      (*info)[i].used_size + (*info)[i].free_size,
01091                      (*info)[i].used_size, (*info)[i].free_size );
01092             message += aux;
01093         }
01094 
01095         if( numberofblocks )
01096         {
01097             sprintf( aux, "| %15u | %18u  ",
01098                      (*info)[i].total_blocks_of_all_disks,
01099                      (*info)[i].free_blocks_of_all_disks );
01100             message += aux;
01101         }
01102         sprintf( aux, "| %3.1f%%\n",
01103                  ( ( (*info)[i].used_blocks_of_all_disks * 100.0 )
01104                  / (*info)[i].total_blocks_of_all_disks) );
01105         message += aux;
01106     }
01107     showMessage( INFO_MSG, message );
01108 }

void RioShell::printDisplayInfo ( DisplayInfo info,
int  start,
bool  showhexadecimal 
) [private]

Definition at line 1240 of file RioShell.cpp.

01242 {
01243     string message;
01244     char aux[ 256 ];
01245 
01246     if( showhexadecimal )
01247     {
01248         sprintf( aux, "%08x: ", start );
01249         message = aux;
01250     }
01251     message += info->data + "\n";
01252     showMessage( INFO_MSG, message );
01253 }

void RioShell::printDuInfo ( vector< DuInfo > *  info,
bool  humanread,
bool  numberofblocks 
) [private]

Definition at line 983 of file RioShell.cpp.

00985 {
00986     char aux[256];
00987     string message;
00988 
00989     for( unsigned int i = 0; i < info->size(); i++ )
00990     {
00991         message += " ";
00992         if( humanread )
00993         {
00994             sprintf( aux, "%11s   ", formatSize( (*info)[i].size ).c_str() );
00995             message += aux;
00996         }
00997         else
00998         {
00999             sprintf( aux, "%11llu   ", (*info)[i].size );
01000             message += aux;
01001         }
01002         if( numberofblocks )
01003         {
01004             sprintf( aux, "%7u   ", (*info)[i].nBlocks );
01005             message += aux;
01006         }
01007         message += (*info)[i].object_name;
01008 
01009         message += "\n";
01010     }
01011     showMessage( INFO_MSG, message );
01012 }

void RioShell::printLsInfo ( vector< ObjectInfo > *  info,
bool  humanread,
bool  numberofblocks,
bool  listinfo,
bool  simplels,
bool  showvideorate,
unsigned int  BlockSize 
) [private]

Definition at line 1114 of file RioShell.cpp.

01118 {
01119     string message;
01120     char aux[256];
01121 
01122     for( unsigned int i = 0; i < info->size(); i++ )
01123     { 
01124         if( listinfo )
01125         {
01126             char type;
01127 
01128             switch( (*info)[i].getType() )
01129             {
01130                 case ObjectInfo::FILE_TYPE_DIRECTORY:
01131                     type = 'd';
01132                     break;
01133                 case ObjectInfo::FILE_TYPE_DATA:
01134                     type = '-';
01135                     break;
01136                 case ObjectInfo::FILE_TYPE_DATA_LINK:
01137                 case ObjectInfo::FILE_TYPE_DIR_LINK:
01138                 case ObjectInfo::FILE_TYPE_BROKEN_LINK:
01139                     type = 'l';
01140                     break;
01141                 default:
01142                     type = '?';
01143                     break;
01144             }
01145 
01146             message = type + short2Permission( (*info)[i].getPermission() );
01147             sprintf( aux, "  %8s %8s ", (*info)[i].getOwner().c_str(),
01148                                         (*info)[i].getGroup().c_str() );
01149             message += aux;
01150 
01151             if( humanread )
01152             {
01153                 sprintf( aux, "%11s   ",
01154                          formatSize( (*info)[i].getSize() ).c_str() );
01155                 message += aux;
01156             }
01157             else
01158             {
01159                 sprintf( aux, "%11llu   ", (*info)[i].getSize() );
01160                 message += aux;
01161             }
01162 
01163             if( numberofblocks )
01164             {
01165                 sprintf( aux, "%7u   ", (unsigned int )
01166                          (( (*info)[i].getSize() + BlockSize - 1 ) / BlockSize)
01167                        );
01168                 message += aux;
01169             }
01170 
01171             sprintf( aux, "%.2d/%.2d/%4d %2d:%.2d  ",
01172                     (*info)[i].getTime().Day,
01173                     (*info)[i].getTime().Month,
01174                     (*info)[i].getTime().Year,
01175                     (*info)[i].getTime().Hour,
01176                     (*info)[i].getTime().Minute );
01177             message += aux;
01178         }
01179 
01180         showMessage( INFO_MSG, message );
01181 
01182         if( !simplels ) //imprimindo ls colorido:
01183         {
01184 
01185             if( ( (*info)[i].getType() == ObjectInfo::FILE_TYPE_DATA_LINK ) ||
01186                 ( (*info)[i].getType() == ObjectInfo::FILE_TYPE_DIR_LINK )
01187               )
01188                 showMessage( INFO_MSG, BLACK_CYAN + (*info)[i].getFullName() + RESET + "@" );
01189             else if( (*info)[i].getType() == ObjectInfo::FILE_TYPE_DIRECTORY )
01190                 showMessage( INFO_MSG, BLACK_BLUE + (*info)[i].getFullName() + RESET + "/" );
01191             else if( (*info)[i].getType() == ObjectInfo::FILE_TYPE_BROKEN_LINK )
01192                 showMessage( INFO_MSG, B_RED_WHITE + (*info)[i].getFullName() + RESET + "@" );
01193             else if( short2Permission( (*info)[i].getPermission() ).find( "x", 0 ) != string::npos )
01194                 showMessage( INFO_MSG, BLACK_GREEN + (*info)[i].getFullName() + RESET + "*" );
01195             else if( ( ( (*info)[i].getName().size() >= 4 ) &&
01196                        (
01197                          ( (*info)[i].getName().substr((*info)[i].getName().size()-4) == ".zip" ) ||
01198                          ( (*info)[i].getName().substr((*info)[i].getName().size()-4) == ".tar" ) ||
01199                          ( (*info)[i].getName().substr((*info)[i].getName().size()-4) == ".tgz" ) ||
01200                          ( (*info)[i].getName().substr((*info)[i].getName().size()-4) == ".arj" )
01201                        )
01202                      ) ||
01203                      ( ( (*info)[i].getName().size() >= 3 ) &&
01204                         ( (*info)[i].getName().substr((*info)[i].getName().size()-3) == ".bz" )
01205                      )
01206                    )
01207                 showMessage( INFO_MSG, BLACK_RED + (*info)[i].getFullName() + RESET );
01208             else
01209                 showMessage( INFO_MSG, (*info)[i].getFullName() );
01210                 
01211         }
01212         else
01213             showMessage( INFO_MSG, (*info)[i].getFullPath() );
01214 
01215         // Mostra a taxa de transmissao de video entre parentesis (somente para 
01216         // os videos .mpg e .mpeg, se o valor booleano showvideorate for true,
01217         // se o valor booleano listinfo para a listagem completa for true, e se 
01218         // o servidor suportar o controle de fluxo (fato indicado por um valor 
01219         // true na variavel booleana UseVideoRate.
01220         if( ( showvideorate ) && ( listinfo ) && ( UseVideoRate ) )
01221         {
01222             // Imprimindo a taxa de transmissao de dados (somente arquivos .mpg e
01223             // .mpeg)
01224             if( ( ( (*info)[i].getName().size() >= 4 ) &&
01225                   ( (*info)[i].getName().substr((*info)[i].getName().size()-4) == ".mpg" ) ) ||
01226                 ( ( (*info)[i].getName().size() >= 5 ) &&
01227                   ( (*info)[i].getName().substr((*info)[i].getName().size()-5) == ".mpeg" ) ) )
01228                 
01229             {
01230                 sprintf(aux, " (%u Kbps)", (*info)[i].getVideoRate() );
01231                 showMessage( INFO_MSG, string( aux ) );
01232             }
01233         }
01234 
01235         showMessage( INFO_MSG, "\n" );
01236 
01237     }
01238 }

void RioShell::printSessionsInfo ( SessionsInfo info  )  [private]

Definition at line 969 of file RioShell.cpp.

00970 {
00971     char aux[256];
00972     string message;
00973 
00974     sprintf( aux, "Número Máximo de Sessões: %10u\n",
00975                    info->number_of_max_sessions );
00976     message = aux;
00977     sprintf( aux, "Número de Sessões Ativas: %10u\n",
00978                    info->number_of_active_sessions );
00979     message += aux;
00980     showMessage( INFO_MSG, message );
00981 }

bool RioShell::resolvePathSession ( CRioSession **  newSession,
char *  ObjectName,
int *  DirType,
CMParser cm = NULL,
unsigned int *  NextPassword = NULL 
) [private]

resolvePathSession analisa o nome ObjectName, verifica se se refere a uma sessão atual(*newSession recebe o session da RioExplorer), se não se refere a nenhuma sessão(*newSession recebe NULL) ou se se refere a uma sessão remota.

Neste último caso, é aberta uma nova sessão com o novo servidor e o ponteiro para esta nova sessão é atribuído a *newSession.

Definition at line 1439 of file RioShell.cpp.

01442 {
01443     char    machine[ MAXNAMELEN ];
01444     // Nova variavel para armazenar o nome do usuario.
01445     char    user[ MAXNAMELEN ];
01446     char   *password;
01447     char   *OptPassValue;
01448     bool    status = true;
01449     string  message;
01450 
01451     *DirType = parsePath( ObjectName, machine, user );
01452     
01453     // Verifica se um usuario foi passado no caminho e, se nenhum usuario foi
01454     // passado, usa o usuario UserName usado ao conectarmos no riosh (neste 
01455     // caso, o usuario retornado sera uma string vazia).
01456     if( strlen( user ) == 0 ) 
01457         strcpy( user, UserName );        
01458 
01459     switch( *DirType )
01460     {
01461         case REMOTE:
01462             password = new char[ MAXNAMELEN ];
01463 
01464             // Check if this ls is from the same remote source
01465             // Password will be prompted again if something differs
01466             if( ( ( strcmp( machine,  lastRemoteAccess.host ) != 0 ) ||
01467                   ( strcmp( UserName, lastRemoteAccess.user ) != 0 ) 
01468                 ) &&
01469                 (  strcmp( UserName, "guest" ) != 0 )
01470               )
01471             {
01472                 // Verifica se uma opcao '-p' foi passada com a senha do 
01473                 // usuario. Como podemos ter mais de uma senha, a variavel
01474                 // NextPassword, se NULL, sera atualizada cada vez que obtemos
01475                 // uma nova senha para, caso a funcao seja chamada novamente no
01476                 // futuro, que o password dado na proxima opcao '-p' seja 
01477                 // usado.
01478                 if( cm != NULL )
01479                 {
01480                     if( NextPassword != NULL )
01481                        OptPassValue = cm->GetOpt( 'p', *NextPassword );
01482                     else
01483                        OptPassValue = cm->GetOpt( 'p' ); 
01484                     
01485                     if( OptPassValue != NULL )
01486                     {
01487                         if( strlen( OptPassValue ) > 0 )  
01488                         {
01489                             #ifdef RIO_DEBUG2
01490                             showMessage( ERROR_MSG, "Option -p, parameter = " );
01491                             showMessage( ERROR_MSG, OptPassValue );
01492                             showMessage( ERROR_MSG, "\n" );
01493                             #endif
01494                         }   
01495                         else
01496                         {
01497                             showMessage( ERROR_MSG, "No param given in " );
01498                             showMessage( ERROR_MSG, "option -p. " );
01499                             OptPassValue = NULL;
01500                         }
01501                         // Como processamos um parametro '-p', entao atualizamos
01502                         // o valor inteiro apontado por NextPassword para 
01503                         // indicar que a proxima chamada a esta funcao deve usar
01504                         // o proximo parametro '-p'.
01505                         if( NextPassword != NULL )
01506                             *NextPassword = *NextPassword + 1;
01507                    }
01508                 } 
01509                 else
01510                     OptPassValue = NULL;
01511 
01512                 // Se nao temos o parametro '-p' ou se nenhuma
01513                 if( OptPassValue == NULL )
01514                 {
01515                     // Ask remote password
01516                     message  = "Type password for ";
01517                     message += user;
01518                     message += "@";
01519                     message += machine;
01520                     message += ": ";
01521                     showMessage( INFO_MSG, message );
01522 
01523                     password = encryptPassword( getpass( "" ) );
01524                 }
01525                 else
01526                     password = encryptPassword( OptPassValue );
01527 
01528                 // Remember last copy data
01529                 strcpy( lastRemoteAccess.host,     machine  );
01530                 strcpy( lastRemoteAccess.user,     user );
01531                 strcpy( lastRemoteAccess.password, password );
01532             }
01533             else
01534             {
01535                 strcpy( password, lastRemoteAccess.password );
01536             }
01537 
01538             *newSession = createSession( machine, user, password );
01539 
01540             if( *newSession == NULL )
01541             {
01542                 message  = "Erro com parâmetro remoto: Impossível criar sessão.\n";
01543                 showMessage( ERROR_MSG, message );
01544                 status = false;
01545             }
01546 
01547             delete password;
01548         break;
01549 
01550         case SERVER:
01551             *newSession = session;
01552             break;
01553 
01554         case LOCAL:
01555             *newSession = NULL;
01556             break;
01557 
01558         case INVALID:
01559             message  = "Erro com nome \"";
01560             message += machine;
01561             message += "\": Formato inválido.\n";
01562             showMessage( ERROR_MSG, message );
01563             status = false;
01564     }
01565 
01566     return status;
01567 }

int RioShell::SearchLogs ( char *  SearchOptionName,
char *  MachineName,
char *  StrStartTime,
char *  StrEndTime,
char *  ResultFileName 
) [private]

Funcao usada para executar o novo comando searchlogs que faz buscas nos logs dos servidores.

Parameters:
SearchOptionName tipo de busca a ser executada. Pode ser clientlogs (busca nos logs de clientes conectados) ou trafficlogs (busca nos logs dos trafegos de dados).
ServerName ponteiro para o nome do servidor em cujos logs desejamos fazer a busca
StrStartTime ponteiro para a string com o tempo inicial para a busca (baseado no mesmo principio da funcao time da biblioteca do C, isto e, o tempo em segundos desde a Epoch (00:00:00 UTC, Janeiro 1 de 1970).
StrEndTime ponteiro para a string com o tempo final para a busca, usando a mesma medida do tempo inicial
ResultFileName ponteiro para o nome do arquivo que armazenara os resultados, caso a busca seja feita com sucesso.
Returns:
igual a RIOSHELL_ERROR se algum erro ocorreu ao exdcutar o comando ou igual a ERROR_NO_RIO_ERROR em caso contrario.

Definition at line 1685 of file RioShell.cpp.

01688 {
01689     // Parametros usados pela busca.
01690 
01691     // string para armazenar as mensagens
01692     string message;
01693     // Endereco IP do servidor.
01694     int ServerIP;
01695     // Porta do servidor
01696     int ServerPort;
01697     // Tipo da busca a ser executada.
01698     int SearchType;
01699     // Posicao da opcao no vetor de opcoes
01700     int Opt;
01701     // Nome do arquivo que armazenara os resultados.
01702     char SearchResultFile[ MaxPathSize ];
01703     // Tempo inicial da busca
01704     time_t StartTime;
01705     // Tempo final da busca
01706     time_t EndTime;
01707     // Armazena a posicao do servidor no vetor com as informacoes dos 
01708     // servidores.
01709     int PosServer;
01710     // Armazena o resultado da execucao da funcao SearchLogs do objeto session.
01711     RioResult hResult;
01712     // Armazena o ip do servidor para ser imprimido.
01713     in_addr ip;
01714     // String para armazenar o numero da porta do servidor (o tamanho e igual a
01715     // 10 por garantia, porque um unsigned int usa 10 caracteres para os seus 
01716     // digitos).
01717     char StrPort[ 10 ];
01718     
01719     // Verifica se o usuario e o root
01720     if( strcmp( UserName, "root" ) != 0 )
01721     {
01722         message = "Only root can execute search in the logs. Current user is "
01723                 + string( UserName ) + "\n";
01724         showMessage( ERROR_MSG, message );
01725         return RIOSHELL_ERROR;
01726     }
01727         
01728     // Obtem a busca a ser executada (que devera ser trafficlogs para as
01729     // buscas nos logs dos servidores de armazenamento ou clientlogs para
01730     // as buscas nos logs do servidor de despacho).
01731     for( Opt = 0; Opt < SEARCHOPTIONSIZE; Opt++ )
01732         if( strcasecmp( SearchOptionName, SearchOption[ Opt ].Name ) == 0 )
01733             break;
01734 
01735     // Obtem a busca associada a opcao.
01736     SearchType = SearchOption[ Opt ].SearchType;
01737     if( SearchType == INVALIDSEARCHTYPE ) 
01738     {
01739         message = "Unknown search type " + string( SearchOptionName ) + "\n";
01740         showMessage( ERROR_MSG, message );
01741         return RIOSHELL_ERROR;
01742     }
01743 
01744     // Obtem o par IP, porta do servidor passado como parametro, e verifica
01745     // se o nome e um nome valido, isto e, se esta associado a um IP.
01746     PosServer = session->CheckServerAddress( MachineName,
01747                                              SearchOption[ Opt ].IsDispatcher,
01748                                              &ServerIP, 
01749                                              &ServerPort );
01750     if( PosServer == -2 ) // Nome da maquina nao existe
01751     {
01752         message = "Can not find host with name " + string( MachineName ) 
01753                 + "\n";
01754         showMessage( ERROR_MSG, message );
01755         return RIOSHELL_ERROR;
01756     } 
01757 
01758     // Verifica agora se o IP associado ao nome e um dos servidores do RIO.
01759     if( PosServer == -1 ) // Maquina nao possui um servidor de despacho ou
01760                             // de armazenamento.
01761     {
01762         message = "Host with name " + string( MachineName ) 
01763                 + " is not a RIO server or storage\n";
01764         showMessage( ERROR_MSG, message );
01765         return RIOSHELL_ERROR;
01766     }  
01767     // Verifica se a busca e valida para o servidor do RIO
01768     if( ( ( PosServer == 0 ) && 
01769           ( SearchOption[ Opt ].SearchType == SEARCHINTRAFFICLOGS ) ) ||
01770         ( ( PosServer > 0 ) && 
01771           ( SearchOption[ Opt ].SearchType == SEARCHINCLIENTSLOGS ) ) )
01772     {
01773         message = "Search type " + string( SearchOptionName ) 
01774                 + " is invalid for server " + string( MachineName ) + "\n";
01775         showMessage( ERROR_MSG, message );
01776         return RIOSHELL_ERROR;
01777     }         
01778         
01779     // Verifica se o tempo final e maior ou igual do que o tempo inicial.
01780     StartTime = atol( StrStartTime );
01781     EndTime = atol( StrEndTime  );
01782     if( StartTime > EndTime )
01783     {
01784         message = "Search start time " + string( StrStartTime ) 
01785                 + " is greather than search end time " + string( StrEndTime ) 
01786                 + "\n";
01787         showMessage( ERROR_MSG, message );
01788         return RIOSHELL_ERROR;
01789     }
01790         
01791     // Copia o nome do arquivo de saida.
01792     strcpy( SearchResultFile, ResultFileName );
01793            
01794     // Executa a busca pedida nos logs do servidor pedido.   
01795     ip.s_addr = ServerIP;
01796     hResult = session->SearchLogs( SearchType, StartTime, EndTime, 
01797                                    ServerIP, ServerPort, 
01798                                    SearchResultFile,
01799                                    SearchLogsCallback, 
01800                                   ( void * ) this );
01801     if( FAILED( hResult ) )
01802     {
01803         message = string( GetErrorDescription( hResult ) )   
01804                 + " error when performing a search";
01805         showMessage( ERROR_MSG, message );
01806         return RIOSHELL_ERROR;
01807     }           
01808      
01809     // Agora usamos o semaforo SearchLogsSemaphore para bloquear o 
01810     // shell ate o termino da busca.
01811     // Imprime as opcoes da busca e a mensagem de espera.
01812     message = "Search type: " + string( SearchOptionName ) + "\nServer: " 
01813             + string( MachineName ) + " (IP: ";
01814     sprintf( StrPort, "%u", ntohs( ServerPort ) ); 
01815     message += string( inet_ntoa( ip ) ) + ", Port: " + string( StrPort ) 
01816             + ")\nStart time: " + string( StrStartTime ) + " - "  
01817             + string( ctime( &StartTime ) ) + "End Time: " 
01818             + string( StrEndTime ) + " - " + string( ctime( &EndTime ) ) 
01819             + "Performing the requested search. Please wait!\n";
01820     showMessage( INFO_MSG, message );
01821 
01822     // Espera pelo termino da busca
01823     SearchLogsSemaphore->P();        
01824       
01825     // Agora devemos verificar o resultado da busca, para ver se ela
01826     // foi feita com sucesso.   
01827     switch( SearchLogsResult ) 
01828     {
01829         case SEARCHLOGSFAILED:
01830             message = "Can not find logs in given time interval\n";
01831             break;
01832         case SEARCHLOGSSUCESS:
01833             message = "Successfully saved in file " + string( SearchResultFile ) 
01834                     + "\n";
01835             break;
01836         case SEARCHLOGSERROR:
01837             message = "An error ocurred when executing the search\n";
01838             break;
01839     }
01840     showMessage( INFO_MSG, message );
01841           
01842     return ERROR_NO_RIO_ERROR;
01843 }

void RioShell::SearchLogsCallback ( void *  param,
int  result 
) [static, private]

Funcao de callback usada quando uma busca nos logs terminar a sua execucao para desbloquear o shell.

Parameters:
param ponteiro (convertido para void) para o objeto RioShell pelo qual a busca foi executada.
result resultado da busca nos logs.

Definition at line 1847 of file RioShell.cpp.

01848 {
01849     RioShell *shell;
01850     
01851     // Converte o ponteiro para o da classe RioShell.
01852     shell = ( RioShell * ) param;
01853     // Copia o resultado da busca na variavel SearchLogsResult.
01854     shell->SearchLogsResult = result;
01855     // Desbloqueia o shell.
01856     shell->SearchLogsSemaphore->V();
01857 }

void RioShell::setMD5Calculation ( char *  object,
bool  finished 
) [private, virtual]

Implements RioExplorer.

Definition at line 1609 of file RioShell.cpp.

01610 {
01611     //the boolean parameter finished indicates if the object has started or
01612     //finished being MD5-hashed
01613     int print_size = 0;
01614 
01615     cout << "\r\033[K";
01616     cout.width( 3 );
01617     cout << 0 << "% [>";
01618     print_size += (3 + 4); //width of number + extra characters
01619 
01620     int i;
01621     for( i = 0; i < PROGRESS_BAR_WIDTH; i++ )
01622          cout << " ";
01623     print_size += PROGRESS_BAR_WIDTH;
01624     if( finished )
01625     {
01626         cout << "] Done MD5sum: ";
01627         print_size += 15; // more characters
01628     }
01629     else
01630     {
01631         cout << "] Calc. MD5sum: ";
01632         print_size += 16; // more characters
01633     }
01634     string current_file = object;
01635     if( current_file.size() + print_size > 80 )
01636     {
01637         current_file.replace( 0, current_file.size() + print_size + 3 - 80,
01638                                    "..." );
01639         cout << current_file.c_str();
01640     }
01641     else
01642         cout << object;
01643     cout.flush();
01644 }

void RioShell::setSyncCheck ( char *  object,
bool  finished 
) [private, virtual]

Implements RioExplorer.

Definition at line 1646 of file RioShell.cpp.

01647 {
01648     //the boolean parameter finished indicates if the object has started or
01649     //finished being MD5-hashed
01650     int print_size = 0;
01651 
01652     cout << "\r\033[K";
01653     cout.width( 3 );
01654     cout << 0 << "% [>";
01655     print_size += (3 + 4); //width of number + extra characters
01656 
01657     int i;
01658     for( i = 0; i < PROGRESS_BAR_WIDTH; i++ )
01659          cout << " ";
01660     print_size += PROGRESS_BAR_WIDTH;
01661     if( finished )
01662     {
01663         cout << "] Checked: ";
01664         print_size += 11; // more characters
01665     }
01666     else
01667     {
01668         cout << "] Checking: ";
01669         print_size += 12; // more characters
01670     }
01671     string current_file = object;
01672     if( current_file.size() + print_size > 80 )
01673     {
01674         current_file.replace( 0, current_file.size() + print_size + 3 - 80,
01675                                    "..." );
01676         cout << current_file.c_str();
01677     }
01678     else
01679     cout << object;
01680     cout.flush();
01681 }

bool RioShell::showMessage ( int  type,
string  message,
string  title = "" 
) [virtual]

Implements RioExplorer.

Definition at line 1276 of file RioShell.cpp.

01277 {
01278     bool status = true;
01279 
01280     switch( type )
01281     {
01282         case ERROR_MSG:
01283         case WARNING_MSG:
01284              cout << message;
01285              break;
01286 
01287         case INFO_MSG:
01288              cout << message;
01289              break;
01290 
01291         case QUESTION_MSG:
01292              char answer[ MAXNAMELEN ];
01293 
01294              cout << message << "(s/n) ";
01295              status = false;
01296              if( fgets( answer, MAXNAMELEN, stdin ) == NULL )
01297              {
01298                  RioErr << "RioShell::showMessage erro ao ler dados de stdin "
01299                         << endl;
01300              }
01301              if( answer[ 0 ] == 's' || answer[ 0 ] == 'S' )
01302                 status = true;
01303 
01304              break;
01305     }
01306 
01307     return status;
01308 }

void RioShell::updateCopyProgress ( void   )  [private, virtual]

Implements RioExplorer.

Definition at line 1569 of file RioShell.cpp.

01570 {
01571     static string last_file = "";
01572     double current_file_ratio;
01573     int print_size = 0;
01574 
01575     // Copy still being performed, print progress
01576     if( current_file_size > 0 )
01577          current_file_ratio = (double) current_file_completed / current_file_size;
01578     else
01579         current_file_ratio = 0;
01580 
01581     cout << "\r\033[K";
01582     cout.width( 3 );
01583     cout << (int)( current_file_ratio * 100 ) << "% [";
01584     print_size += (3 + 3); //width of number + extra characters
01585     int i;
01586     for( i = 0;
01587          i < (int)( PROGRESS_BAR_WIDTH * current_file_ratio );
01588          i++ )
01589          cout << "=";
01590     cout << ">";
01591     print_size += 1;
01592     for( ; i < PROGRESS_BAR_WIDTH; i++ )
01593          cout << " ";
01594     print_size += PROGRESS_BAR_WIDTH; // progress bar
01595     cout << "] Copying ";
01596     print_size += 10; // more characters
01597     if( current_file.size() + print_size > 80 )
01598     {
01599         string current_file_copy = current_file;
01600         current_file_copy.replace( 0, current_file.size() + print_size + 3 - 80,
01601                                    "..." );
01602         cout << current_file_copy.c_str();
01603     }
01604     else
01605     cout << current_file.c_str();
01606     cout.flush();
01607 }


Field Documentation

bool RioShell::copy_allowed [private]

Definition at line 128 of file RioShell.h.

string RioShell::current_file [private]

Definition at line 121 of file RioShell.h.

Definition at line 122 of file RioShell.h.

Definition at line 123 of file RioShell.h.

Definition at line 148 of file RioShell.h.

struct { ... } RioShell::lastRemoteAccess [private]
char* RioShell::MachineName [private]

Definition at line 125 of file RioShell.h.

Definition at line 150 of file RioShell.h.

char* RioShell::Password [private]

Definition at line 127 of file RioShell.h.

const int RioShell::PROGRESS_BAR_WIDTH = 25 [static, private]

Definition at line 144 of file RioShell.h.

Definition at line 136 of file RioShell.h.

Definition at line 140 of file RioShell.h.

const int RioShell::UPDATE_INTERVAL = 50000 [static, private]

Definition at line 143 of file RioShell.h.

Definition at line 149 of file RioShell.h.

char* RioShell::UserName [private]

Definition at line 126 of file RioShell.h.

bool RioShell::UseVideoRate [private]

Definition at line 132 of file RioShell.h.


The documentation for this class was generated from the following files:
Generated on Wed Jul 4 16:03:37 2012 for RIO by  doxygen 1.6.3