private long sumIndexFiles( File file, FilenameFilter filter ) { long total = 0; if ( outsideWorld.fileSystem().isDirectory( file ) ) { File[] children = outsideWorld.fileSystem().listFiles( file, filter ); if ( children != null ) { for ( File child : children ) { total += sumIndexFiles( child, filter ); } } } else { total += outsideWorld.fileSystem().getFileSize( file ); } return total; }
@Test public void shouldErrorWithNoSuchUser() { tool.execute( homeDir.toPath(), confDir.toPath(), SET_ADMIN, "bob" ); verify( out ).stdErrLine( "command failed: no such user: 'bob'" ); verify( out ).exit( 1 ); verify( out, never() ).stdOutLine( anyString() ); }
DiagnosticsReportCommand( Path homeDir, Path configDir, OutsideWorld outsideWorld ) { this.homeDir = homeDir; this.configDir = configDir; this.fs = outsideWorld.fileSystem(); this.out = outsideWorld.outStream(); err = outsideWorld.errorStream(); }
private void failure( String message, int code ) { outsideWorld.stdErrLine( message ); outsideWorld.exit( code ); }
private void setDefaultAdmin( String username ) throws Throwable FileSystemAbstraction fileSystem = outsideWorld.fileSystem(); Config config = loadNeo4jConfig(); admins.shutdown(); outsideWorld.stdOutLine( "default admin user set to '" + username + "'" );
private void print( String text ) { outsideWorld.stdOutLine( text ); }
@Test void versionArgumentPrintsVersion() { AdminCommand command = mock( AdminCommand.class ); OutsideWorld outsideWorld = mock( OutsideWorld.class ); new AdminTool( cannedCommand( "command", command ), new NullBlockerLocator(), outsideWorld, false ) .execute( null, null, "--version" ); verifyNoMoreInteractions( command ); verify( outsideWorld ).stdOutLine( "neo4j-admin " + neo4jVersion() ); verify( outsideWorld ).exit( STATUS_SUCCESS ); }
@Override public void doImport() throws IOException { FileSystemAbstraction fs = outsideWorld.fileSystem(); File storeDir = databaseConfig.get( GraphDatabaseSettings.database_path ); File logsDir = databaseConfig.get( GraphDatabaseSettings.logs_directory ); File reportFile = new File( reportFileName ); OutputStream badOutput = new BufferedOutputStream( fs.openAsOutputStream( reportFile, false ) ); Collector badCollector = badCollector( badOutput, isIgnoringSomething() ? BadCollector.UNLIMITED_TOLERANCE : 0, collect( ignoreBadRelationships, ignoreDuplicateNodes, ignoreExtraColumns ) ); Configuration configuration = new WrappedBatchImporterConfigurationForNeo4jAdmin( importConfiguration( null, false, databaseConfig, storeDir, highIO ) ); // Extract the default time zone from the database configuration ZoneId dbTimeZone = databaseConfig.get( GraphDatabaseSettings.db_temporal_timezone ); Supplier<ZoneId> defaultTimeZone = () -> dbTimeZone; CsvInput input = new CsvInput( nodeData( inputEncoding, nodesFiles ), defaultFormatNodeFileHeader( defaultTimeZone ), relationshipData( inputEncoding, relationshipsFiles ), defaultFormatRelationshipFileHeader( defaultTimeZone ), idType, new WrappedCsvInputConfigurationForNeo4jAdmin( csvConfiguration( args, false ) ), badCollector ); ImportTool.doImport( outsideWorld.errorStream(), outsideWorld.errorStream(), outsideWorld.inStream(), DatabaseLayout.of( storeDir ), logsDir, reportFile, fs, nodesFiles, relationshipsFiles, false, input, this.databaseConfig, badOutput, configuration, false ); }
@Test void listShouldDisplayAllClassifiers() throws Exception { try ( ByteArrayOutputStream baos = new ByteArrayOutputStream() ) { PrintStream ps = new PrintStream( baos ); String[] args = {"--list"}; OutsideWorld outsideWorld = mock( OutsideWorld.class ); when( outsideWorld.fileSystem() ).thenReturn( fs ); when( outsideWorld.outStream() ).thenReturn( ps ); DiagnosticsReportCommand diagnosticsReportCommand = new DiagnosticsReportCommand( homeDir, configDir, outsideWorld ); diagnosticsReportCommand.execute( args ); assertThat( baos.toString(), is(String.format( "Finding running instance of neo4j%n" + "No running instance of neo4j was found. Online reports will be omitted.%n" + "If neo4j is running but not detected, you can supply the process id of the running instance with --pid%n" + "All available classifiers:%n" + " config include configuration file%n" + " logs include log files%n" + " plugins include a view of the plugin directory%n" + " ps include a list of running processes%n" + " tree include a view of the tree structure of the data directory%n" + " tx include transaction logs%n" ) ) ); } }
outsideWorld.stdOutLine( "neo4j-admin " + neo4jVersion() ); success(); return; outsideWorld.stdErrLine( "unknown argument: --help" ); usage.printUsageForCommand( provider, outsideWorld::stdErrLine ); failure();
/** * Construct a wrapper of supported backup strategies * * @param onlineBackupContext the input of the backup tool, such as CLI arguments, config etc. * @param backupProtocolService the underlying backup implementation for HA and single node instances * @param backupDelegator the backup implementation used for CC backups * @param pageCache the page cache used moving files * @return strategy coordinator that handles the which backup strategies are tried and establishes if a backup was successful or not */ BackupStrategyCoordinator backupStrategyCoordinator( OnlineBackupContext onlineBackupContext, BackupProtocolService backupProtocolService, BackupDelegator backupDelegator, PageCache pageCache ) { FileSystemAbstraction fs = outsideWorld.fileSystem(); BackupCopyService copyService = new BackupCopyService( fs, pageCache, new FileMoveProvider( pageCache, fs ) ); ProgressMonitorFactory progressMonitorFactory = ProgressMonitorFactory.textual( outsideWorld.errorStream() ); BackupRecoveryService recoveryService = new BackupRecoveryService(); long timeout = onlineBackupContext.getRequiredArguments().getTimeout(); Config config = onlineBackupContext.getConfig(); StoreFiles storeFiles = new StoreFiles( fs, pageCache ); BackupStrategy ccStrategy = new CausalClusteringBackupStrategy( backupDelegator, addressResolver, logProvider, storeFiles ); BackupStrategy haStrategy = new HaBackupStrategy( backupProtocolService, addressResolver, logProvider, timeout ); BackupStrategyWrapper ccStrategyWrapper = wrap( ccStrategy, copyService, pageCache, config, recoveryService ); BackupStrategyWrapper haStrategyWrapper = wrap( haStrategy, copyService, pageCache, config, recoveryService ); StrategyResolverService strategyResolverService = new StrategyResolverService( haStrategyWrapper, ccStrategyWrapper ); List<BackupStrategyWrapper> strategies = strategyResolverService.getStrategies( onlineBackupContext.getRequiredArguments().getSelectedBackupProtocol() ); return new BackupStrategyCoordinator( consistencyCheckService, outsideWorld, logProvider, progressMonitorFactory, strategies ); }
private void success() { outsideWorld.exit( STATUS_SUCCESS ); } }
BackupOutputMonitor( OutsideWorld outsideWorld ) { LogProvider stdOutLogProvider = FormattedLogProvider.toOutputStream( outsideWorld.outStream() ); log = stdOutLogProvider.getLog( BackupOutputMonitor.class ); }
private void failure( String message, Exception e, int code ) { if ( debug ) { outsideWorld.printStacktrace( e ); } failure( format( "%s: %s", message, e.getMessage() ), code ); }
private void badUsage( AdminCommand.Provider command, IncorrectUsage e ) { outsideWorld.stdErrLine( e.getMessage() ); outsideWorld.stdErrLine( "" ); usage.printUsageForCommand( command, outsideWorld::stdErrLine ); failure(); }
CsvImporter( Args args, Config databaseConfig, OutsideWorld outsideWorld ) throws IncorrectUsage { this.args = args; this.outsideWorld = outsideWorld; nodesFiles = extractInputFiles( args, "nodes", outsideWorld.errorStream() ); relationshipsFiles = extractInputFiles( args, "relationships", outsideWorld.errorStream() ); reportFileName = args.interpretOption( "report-file", withDefault( ImportCommand.DEFAULT_REPORT_FILE_NAME ), s -> s ); ignoreExtraColumns = args.getBoolean( "ignore-extra-columns", false ); ignoreDuplicateNodes = args.getBoolean( "ignore-duplicate-nodes", false ); ignoreBadRelationships = args.getBoolean( "ignore-missing-nodes", false ); try { validateInputFiles( nodesFiles, relationshipsFiles ); } catch ( IllegalArgumentException e ) { throw new IncorrectUsage( e.getMessage() ); } idType = args.interpretOption( "id-type", withDefault( IdType.STRING ), from -> IdType.valueOf( from.toUpperCase() ) ); inputEncoding = Charset.forName( args.get( "input-encoding", defaultCharset().name() ) ); highIO = args.getBoolean( "high-io", null, true ); // intentionally left as null if not specified this.databaseConfig = databaseConfig; }
private void setPassword( String password ) throws Throwable { Config config = loadNeo4jConfig(); FileSystemAbstraction fileSystem = outsideWorld.fileSystem(); if ( realUsersExist( config ) ) { File authFile = CommunitySecurityModule.getUserRepositoryFile( config ); throw new CommandFailed( realUsersExistErrorMsg( fileSystem, authFile ) ); } else { File file = CommunitySecurityModule.getInitialUserRepositoryFile( config ); if ( fileSystem.fileExists( file ) ) { fileSystem.deleteFile( file ); } FileUserRepository userRepository = new FileUserRepository( fileSystem, file, NullLogProvider.getInstance() ); userRepository.start(); userRepository.create( new User.Builder( INITIAL_USER_NAME, LegacyCredential.forPassword( UTF8.encode( password ) ) ) .withRequiredPasswordChange( false ) .build() ); userRepository.shutdown(); outsideWorld.stdOutLine( "Changed password for user '" + INITIAL_USER_NAME + "'." ); } }
@Test public void shouldSetPassword() throws Throwable { tool.execute( homeDir.toPath(), confDir.toPath(), SET_PASSWORD, "abc" ); assertAuthIniFile( "abc" ); verify( out ).stdOutLine( "Changed password for user 'neo4j'." ); }
@Test void helpArgumentPrintsHelp() { AdminCommand command = mock( AdminCommand.class ); OutsideWorld outsideWorld = mock( OutsideWorld.class ); new AdminTool( cannedCommand( "command", command ), new NullBlockerLocator(), outsideWorld, false ) .execute( null, null, "--help" ); verifyNoMoreInteractions( command ); verify( outsideWorld ).stdErrLine( "unrecognized command: --help" ); verify( outsideWorld ).stdErrLine( "usage: neo4j-admin <command>" ); verify( outsideWorld ).exit( STATUS_ERROR ); }
@Test void versionArgumentPrintsVersionEvenWithCommand() { AdminCommand command = mock( AdminCommand.class ); OutsideWorld outsideWorld = mock( OutsideWorld.class ); new AdminTool( cannedCommand( "command", command ), new NullBlockerLocator(), outsideWorld, false ) .execute( null, null, "command", "--version" ); verifyNoMoreInteractions( command ); verify( outsideWorld ).stdOutLine( "neo4j-admin " + neo4jVersion() ); verify( outsideWorld ).exit( STATUS_SUCCESS ); }