3
d                 @   s   d Z ddlZddlZddlmZ ddlZddlZddlmZ ddl	m
Z
 ddlmZ ddlmZmZ ejd	Zdd
dZdd ZdddZdS )z&Common graph operations for execution
    N)gethostname)strftime)format_exception   )logging)savepkl	crash2txtznipype.workflowc             C   s  | j }d}|pttj  }y
| j}W nZ tk
rH   |djdd7 }Y nf tk
r~ } z|dj|jdd7 }W Y dd}~X n0X t	|ddrt
|jtr|jd j}n|jj}|p|pt }tjd|| td	}ytj }W n$ tk
r   d
jtj }Y nX d|||ttj f }	| jd jdtj }
tj|
dd tjj|
|	}	| jd d j  dkrp|	d7 }	n|	d7 }	tjd|	dj| |	j!drt"|	t#| |d nt$|	t#| |ddd |	S )z*Writes crash related information to a fileNz^

When creating this crashfile, the results file corresponding
to the node could not be found.T)keependszj

During the creation of this crashfile triggered by the above exception,
another exception occurred:

{}.runtimer   z!Node %s failed to run on host %s.z%Y%m%d-%H%M%SzUID{:d}zcrash-%s-%s-%s-%s	executionZcrashdump_dir)exist_okZcrashfile_formattexttxt.txtz.pklzzSaving crash info to %s
%s )node	traceback)Z
versioning)r   r   r   )%_idr   sysexc_inforesultFileNotFoundError
splitlines	Exceptionformatgetattr
isinstancer
   listhostnamer   loggererrorr   getpassgetuserKeyErrorosgetuidstruuiduuid4configgetgetcwdmakedirspathjoinlowerendswithr   dictr   )r   r   r   namehostr   excZtimeofcrashZ
login_name	crashfileZcrashdir r6   ?/tmp/pip-build-7vycvbft/nipype/nipype/pipeline/plugins/tools.pyreport_crash   sJ    

r8   c             C   s   | rt jd xj| D ]b}t jddj|d j|d jf  t jd|d   t jd x|d D ]}t j|j qbW qW t jd d	S )
zList nodes that crashed with crashfile info

    Optionally displays dependent nodes that weren't executed as a result of
    the crash.
    z#***********************************zcould not run node: %s.r   zcrashfile: %sr5   z*The following dependent nodes were not runZ
dependentsN)r   infor    r.   
_hierarchyr   debug)Znotrunr:   Zsubnoder6   r6   r7   report_nodes_not_runN   s    


r=   FTc          	   C   s
  t d}| jr@d|| j| jf }tjj| j| jjdd d}nd|| jf }tjj| jd}tjj|sttj	| tjj|d| }t
|t| |d | jd	 d
 }d}|r|d7 }n|d7 }||||| j|f }tjj|d| }	t|	d}
|
j| W d Q R X |	S )Nz%Y%m%d_%H%M%Sz%s_%s_%sr9   r   batchz%s_%sznode_%s.pklz)r   
updatehashr   Zmatplotlib_backenda  import os
import sys

can_import_matplotlib = True #Silently allow matplotlib to be ignored
try:
    import matplotlib
    matplotlib.use('%s')
except ImportError:
    can_import_matplotlib = False
    pass

import os
value = os.environ.get('NIPYPE_NO_ET', None)
if value is None:
    # disable ET for any submitted job
    os.environ['NIPYPE_NO_ET'] = "1"
from nipype import config, logging

from nipype.utils.filemanip import loadpkl, savepkl
from socket import gethostname
from traceback import format_exception
info = None
pklfile = '%s'
batchdir = '%s'
from nipype.utils.filemanip import loadpkl, savepkl
try:
    from collections import OrderedDict
    config_dict=%s
    config.update_config(config_dict)
    ## Only configure matplotlib if it was successfully imported,
    ## matplotlib is an optional component to nipype
    if can_import_matplotlib:
        config.update_matplotlib()
    logging.update_logging(config)
    traceback=None
    cwd = os.getcwd()
    info = loadpkl(pklfile)
    result = info['node'].run(updatehash=info['updatehash'])
except Exception as e:
    etype, eval, etr = sys.exc_info()
    traceback = format_exception(etype,eval,etr)
    if info is None or not os.path.exists(info['node'].output_dir()):
        result = None
        resultsfile = os.path.join(batchdir, 'crashdump_%s.pklz')
    else:
        result = info['node'].result
        resultsfile = os.path.join(info['node'].output_dir(),
                               'result_%%s.pklz'%%info['node'].name)
zz
    savepkl(resultsfile, dict(result=result, hostname=gethostname(),
                              traceback=traceback))
a/  
    if info is None:
        savepkl(resultsfile, dict(result=result, hostname=gethostname(),
                              traceback=traceback))
    else:
        from nipype.pipeline.plugins.base import report_crash
        report_crash(info['node'], traceback, gethostname())
    raise Exception(e)
zpyscript_%s.pywt)r   r;   r   r$   r-   r.   base_dirsplitexistsr,   r   r1   r)   open
writelines)r   r?   Zstore_exception	timestampsuffixZ	batch_dirZpkl_fileZmpl_backendZcmdstrZpyscriptfpr6   r6   r7   create_pyscriptb   s,     
2rI   )NN)FT)__doc__r$   r!   socketr   r   r'   timer   r   r   r   r   Zutils.filemanipr   r   	getLoggerr   r8   r=   rI   r6   r6   r6   r7   <module>   s   

: