<commit_before>/**
 * Copyright (c) 2002-2014 "Neo Technology,"
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Neo4j is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.neo4j.unsafe.impl.batchimport;

import java.io.IOException;
import java.util.Iterator;

import org.neo4j.helpers.Exceptions;
import org.neo4j.kernel.impl.nioneo.store.FileSystemAbstraction;
import org.neo4j.kernel.impl.nioneo.store.NodeStore;
import org.neo4j.kernel.impl.nioneo.store.PropertyStore;
import org.neo4j.kernel.impl.nioneo.store.RelationshipStore;
import org.neo4j.kernel.lifecycle.LifeSupport;
import org.neo4j.kernel.logging.ConsoleLogger;
import org.neo4j.kernel.logging.Logging;
import org.neo4j.unsafe.impl.batchimport.cache.IdMapper;
import org.neo4j.unsafe.impl.batchimport.cache.LongArrayFactory;
import org.neo4j.unsafe.impl.batchimport.cache.NodeRelationshipLink;
import org.neo4j.unsafe.impl.batchimport.cache.NodeRelationshipLinkImpl;
import org.neo4j.unsafe.impl.batchimport.input.InputNode;
import org.neo4j.unsafe.impl.batchimport.input.InputRelationship;
import org.neo4j.unsafe.impl.batchimport.staging.ExecutionMonitor;
import org.neo4j.unsafe.impl.batchimport.staging.IteratorBatcherStep;
import org.neo4j.unsafe.impl.batchimport.staging.Stage;
import org.neo4j.unsafe.impl.batchimport.staging.StageExecution;
import org.neo4j.unsafe.impl.batchimport.store.BatchingNeoStore;
import org.neo4j.unsafe.impl.batchimport.store.io.IoMonitor;
import org.neo4j.unsafe.impl.batchimport.store.io.IoQueue;

import static java.lang.System.currentTimeMillis;

import static org.neo4j.graphdb.factory.GraphDatabaseSettings.store_dir;
import static org.neo4j.helpers.collection.MapUtil.stringMap;
import static org.neo4j.kernel.logging.DefaultLogging.createDefaultLogging;

/**
 * Overall goals: split up processing cost by parallelizing. Keep CPUs busy, keep I/O busy and writing sequentially.
 * Goes through multiple stages where each stage has one or more steps executing in parallel, passing
 * batches downstream.
 */
public class ParallelBatchImporter implements BatchImporter
{
    private final String storeDir;
    private final FileSystemAbstraction fileSystem;
    private final Configuration config;
    private final IoMonitor writeMonitor;
    private final ExecutionMonitor executionMonitor;
    private final Logging logging;
    private final ConsoleLogger logger;
    private final LifeSupport life = new LifeSupport();
    private final IoQueue writerFactory;

    public ParallelBatchImporter( String storeDir, FileSystemAbstraction fileSystem,
                                  Configuration config, ExecutionMonitor executionMonitor )
    {
        this.storeDir = storeDir;
        this.fileSystem = fileSystem;
        this.config = config;
        this.logging = life.add( createDefaultLogging( stringMap( store_dir.name(), storeDir ) ) );
        this.logger = logging.getConsoleLog( getClass() );
        this.executionMonitor = executionMonitor;
        this.writeMonitor = new IoMonitor();
        this.writerFactory = new IoQueue( config.numberOfIoThreads() );

        life.start();
    }

    @Override
    public void doImport( Iterable<InputNode> nodes, Iterable<InputRelationship> relationships,
                          IdMapper idMapper ) throws IOException
    {
        // TODO log about import starting

        long startTime = currentTimeMillis();
        try ( BatchingNeoStore neoStore = new BatchingNeoStore( fileSystem, storeDir, config,
                writeMonitor, logging, writerFactory ) )
        {
            // Stage 1 -- nodes, properties, labels
            NodeStage nodeStage = new NodeStage( idMapper.wrapNodes( nodes.iterator() ), neoStore );

            // Stage 2 -- calculate dense node threshold
            NodeRelationshipLink nodeRelationshipLink = new NodeRelationshipLinkImpl(
                    LongArrayFactory.AUTO, config.denseNodeThreshold() );
            CalculateDenseNodesStage calculateDenseNodesStage = new CalculateDenseNodesStage(
                    relationships.iterator(), nodeRelationshipLink );
            executeStages( nodeStage, calculateDenseNodesStage );

            // Stage 3 -- relationships, properties
            executeStages( new RelationshipStage( idMapper.wrapRelationships( relationships.iterator() ),
                    neoStore, nodeRelationshipLink ) );

            // Switch to reverse updating mode
            neoStore.switchNodeAndRelationshipStoresToUpdateMode();

            // Stage 4 -- set node nextRel fields
            executeStages( new NodeFirstRelationshipStage( neoStore, nodeRelationshipLink ) );

            // Stage 5 -- link relationship chains together
            nodeRelationshipLink.clearRelationships();
            executeStages( new RelationshipLinkbackStage( neoStore, nodeRelationshipLink ) );

            executionMonitor.done( currentTimeMillis() - startTime );

            logger.log( "Import completed [TODO import stats]" );
        }
        catch ( Throwable t )
        {
            logger.error( "Error during import", t );
            throw Exceptions.launderedException( IOException.class, t );
        }
        finally
        {
            writerFactory.shutdownAndAwaitEverythingWritten();
        }
    }

    private synchronized void executeStages( Stage... stages ) throws Exception
    {
        StageExecution[] executions = new StageExecution[stages.length];
        for ( int i = 0; i < stages.length; i++ )
        {
            executions[i] = stages[i].execute();
        }

        executionMonitor.monitor( executions );
    }

    @Override<commit_msg>Removed a TODO from a log statement<commit_after>/**
 * Copyright (c) 2002-2014 "Neo Technology,"
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Neo4j is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.neo4j.unsafe.impl.batchimport;

import java.io.IOException;
import java.util.Iterator;

import org.neo4j.helpers.Exceptions;
import org.neo4j.kernel.impl.nioneo.store.FileSystemAbstraction;
import org.neo4j.kernel.impl.nioneo.store.NodeStore;
import org.neo4j.kernel.impl.nioneo.store.PropertyStore;
import org.neo4j.kernel.impl.nioneo.store.RelationshipStore;
import org.neo4j.kernel.lifecycle.LifeSupport;
import org.neo4j.kernel.logging.ConsoleLogger;
import org.neo4j.kernel.logging.Logging;
import org.neo4j.unsafe.impl.batchimport.cache.IdMapper;
import org.neo4j.unsafe.impl.batchimport.cache.LongArrayFactory;
import org.neo4j.unsafe.impl.batchimport.cache.NodeRelationshipLink;
import org.neo4j.unsafe.impl.batchimport.cache.NodeRelationshipLinkImpl;
import org.neo4j.unsafe.impl.batchimport.input.InputNode;
import org.neo4j.unsafe.impl.batchimport.input.InputRelationship;
import org.neo4j.unsafe.impl.batchimport.staging.ExecutionMonitor;
import org.neo4j.unsafe.impl.batchimport.staging.IteratorBatcherStep;
import org.neo4j.unsafe.impl.batchimport.staging.Stage;
import org.neo4j.unsafe.impl.batchimport.staging.StageExecution;
import org.neo4j.unsafe.impl.batchimport.store.BatchingNeoStore;
import org.neo4j.unsafe.impl.batchimport.store.io.IoMonitor;
import org.neo4j.unsafe.impl.batchimport.store.io.IoQueue;

import static java.lang.System.currentTimeMillis;

import static org.neo4j.graphdb.factory.GraphDatabaseSettings.store_dir;
import static org.neo4j.helpers.collection.MapUtil.stringMap;
import static org.neo4j.kernel.logging.DefaultLogging.createDefaultLogging;

/**
 * Overall goals: split up processing cost by parallelizing. Keep CPUs busy, keep I/O busy and writing sequentially.
 * Goes through multiple stages where each stage has one or more steps executing in parallel, passing
 * batches downstream.
 */
public class ParallelBatchImporter implements BatchImporter
{
    private final String storeDir;
    private final FileSystemAbstraction fileSystem;
    private final Configuration config;
    private final IoMonitor writeMonitor;
    private final ExecutionMonitor executionMonitor;
    private final Logging logging;
    private final ConsoleLogger logger;
    private final LifeSupport life = new LifeSupport();
    private final IoQueue writerFactory;

    public ParallelBatchImporter( String storeDir, FileSystemAbstraction fileSystem,
                                  Configuration config, ExecutionMonitor executionMonitor )
    {
        this.storeDir = storeDir;
        this.fileSystem = fileSystem;
        this.config = config;
        this.logging = life.add( createDefaultLogging( stringMap( store_dir.name(), storeDir ) ) );
        this.logger = logging.getConsoleLog( getClass() );
        this.executionMonitor = executionMonitor;
        this.writeMonitor = new IoMonitor();
        this.writerFactory = new IoQueue( config.numberOfIoThreads() );

        life.start();
    }

    @Override
    public void doImport( Iterable<InputNode> nodes, Iterable<InputRelationship> relationships,
                          IdMapper idMapper ) throws IOException
    {
        // TODO log about import starting

        long startTime = currentTimeMillis();
        try ( BatchingNeoStore neoStore = new BatchingNeoStore( fileSystem, storeDir, config,
                writeMonitor, logging, writerFactory ) )
        {
            // Stage 1 -- nodes, properties, labels
            NodeStage nodeStage = new NodeStage( idMapper.wrapNodes( nodes.iterator() ), neoStore );

            // Stage 2 -- calculate dense node threshold
            NodeRelationshipLink nodeRelationshipLink = new NodeRelationshipLinkImpl(
                    LongArrayFactory.AUTO, config.denseNodeThreshold() );
            CalculateDenseNodesStage calculateDenseNodesStage = new CalculateDenseNodesStage(
                    relationships.iterator(), nodeRelationshipLink );
            executeStages( nodeStage, calculateDenseNodesStage );

            // Stage 3 -- relationships, properties
            executeStages( new RelationshipStage( idMapper.wrapRelationships( relationships.iterator() ),
                    neoStore, nodeRelationshipLink ) );

            // Switch to reverse updating mode
            neoStore.switchNodeAndRelationshipStoresToUpdateMode();

            // Stage 4 -- set node nextRel fields
            executeStages( new NodeFirstRelationshipStage( neoStore, nodeRelationshipLink ) );

            // Stage 5 -- link relationship chains together
            nodeRelationshipLink.clearRelationships();
            executeStages( new RelationshipLinkbackStage( neoStore, nodeRelationshipLink ) );

            executionMonitor.done( currentTimeMillis() - startTime );

            // TODO add import starts to this log message
            logger.log( "Import completed" );
        }
        catch ( Throwable t )
        {
            logger.error( "Error during import", t );
            throw Exceptions.launderedException( IOException.class, t );
        }
        finally
        {
            writerFactory.shutdownAndAwaitEverythingWritten();
        }
    }

    private synchronized void executeStages( Stage... stages ) throws Exception
    {
        StageExecution[] executions = new StageExecution[stages.length];
        for ( int i = 0; i < stages.length; i++ )
        {
            executions[i] = stages[i].execute();
        }

        executionMonitor.monitor( executions );
    }

    @Override
{'fraction_non_alphanumeric': 0.08187876864487464, 'fraction_numerical': 0.006664550936210727, 'mean_word_length': 3.211493484797862, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '22229', 'n_tokens_mistral': 3405, 'n_tokens_neox': 3263, 'n_words': 894}