Welcome    Usage    Browse    Find CID    Search     Log in

cM API Documentation

module.py

Go to the documentation of this file.
00001 #
00002 # Collective Mind
00003 #
00004 # See cM LICENSE.txt for licensing details.
00005 # See cM Copyright.txt for copyright details.
00006 #
00007 # Developer(s): (C) Grigori Fursin, started on 2011.09
00008 #
00009 
00010 import os
00011 import json
00012 import zipfile
00013 import time
00014 import copy as xcopy # since we have "copy" function in this module
00015 
00016 ini={}
00017 cm_kernel=None
00018 
00019 # ============================================================================
00020 def init(i):
00021 
00022     return {'cm_return':0}
00023 
00024 # ============================================================================
00025 def add_data(i):
00026 
00027     """
00028     Add repository
00029 
00030     Input:  {
00031               (path)        - path to create repository (otherwise current) or URL
00032               path_type     - absolute, relative_to_cm, remote_url
00033               (cm_repo_uoa) - repo UOA where to create entry
00034               (cm_array)    - additional description
00035               (repo_alias)  - alias on the disk
00036               (repo_name)   - user friendly name (when listing repositories)
00037               (repo_uid)    - set UID for the repository - useful 
00038                               when creating personal user repository in shared environments ...
00039             }
00040 
00041     Output: {
00042               cm_return  - return code >0 if error
00043               cm_path    - path to created data entry
00044               ...        - other paramaters from core add_data function
00045             }
00046     """
00047 
00048     # If web access, move to 'core' module
00049     if i.get('cm_console','')=='web':
00050        i['cm_run_module_uoa']=ini['cfg']['cm_modules']['cm-core']
00051        i['cm_action']='add'
00052        i['cm_subaction_add']='yes'
00053        return cm_kernel.access(i)
00054 
00055     # Check if cm_array or CMD
00056     if 'cm_array' in i: ir=i['cm_array']
00057     else: 
00058        # FGG: in original cM I was adding everything from CMD to the entry
00059        # but at the end it was too messy, so we only add to entry from cm_array now
00060        #ir=i
00061        ir={}
00062     if i.get('path_type','')!='': ir['path_type']=i['path_type']
00063     if i.get('path','')!='': ir['path']=i['path']
00064 
00065     # Second, process request
00066     # Prepar path
00067     p=os.getcwd()
00068     if 'path' in ir: p=ir['path']
00069     else: ir['path']=p
00070 
00071     if ir.get('path_type','')=='relative_to_cm':
00072        p=cm_kernel.ini[cm_kernel.env_cm_root]
00073        if ir.get('path','')!='':
00074           p=os.path.join(p, ir['path'])
00075 
00076     path_type=''
00077     if 'path_type' in ir: path_type=ir['path_type']
00078     else: ir['path_type']='absolute'
00079 
00080     if path_type=='':
00081        return {'cm_return':1, 'cm_error':'path type is not defined'}
00082     elif path_type=='remote_url':
00083        p=''
00084 
00085     # Check if directory already exists
00086     if path_type!='remote_url':
00087        p1=os.path.join(p, cm_kernel.ini['dcfg']['cmr_ext'])
00088 
00089        found=False
00090        if os.path.isdir(p):
00091           # Check if exist in the repository
00092           r=get_all_repo_paths({})
00093           if r['cm_return']>0: return r
00094 
00095           all=r['cm_array']
00096 
00097           for x in all:
00098               if 'cm_path_without_cmr' in x and os.path.isdir(x['cm_path_without_cmr']) and os.stat(x['cm_path_without_cmr'])==os.stat(p):
00099                  found=True
00100                  break 
00101 
00102           if found:
00103              if not os.path.isdir(p1): os.makedirs(p1)
00104 
00105              return {'cm_return':1, 'cm_error':'repository already exist at this path '+p1}
00106 
00107     if ir.get('repo_name','')!='': ir['cm_display_as_alias']=ir['repo_name']
00108 
00109     # Go to common core function to create entry
00110     ii={};ii.update(i)
00111     if ir.get('repo_alias','')!='': ii['cm_data_uoa']=ir['repo_alias']
00112     if ir.get('repo_uid','')!='': ii['cm_data_uid']=ir['repo_uid']
00113     ii['cm_run_module_uoa']=ini['cfg']['cm_modules']['cm-core']
00114     ii['cm_module_uoa']=i['cm_run_module_uoa']
00115     ii['cm_array']=ir
00116     ii['use_default_repo']='yes' # Always create repository in default repo!
00117     r=cm_kernel.access(ii)
00118     if r['cm_return']>0: return r
00119 
00120     # Create directory
00121     print p1
00122     x=''
00123     if path_type!='remote_url' and not found and not os.path.isdir(p1):
00124        os.makedirs(p1)
00125        x=' at '+p1
00126 
00127     if i.get('cm_console','')=='txt':
00128        cm_kernel.print_for_con('Repository successfully created'+x)
00129 
00130     return r
00131 
00132 # ============================================================================
00133 def update_data(i):
00134 
00135     """
00136     Update repository
00137 
00138     Input:  {
00139             }
00140 
00141     Output: {
00142             }
00143     """
00144 
00145     # If web access, move to 'core' module
00146     if i.get('cm_console','')=='web':
00147        i['cm_run_module_uoa']=ini['cfg']['cm_modules']['cm-core']
00148        i['cm_action']='update'
00149        return cm_kernel.access(i)
00150 
00151     # Check if cm_array or CMD
00152     if 'cm_array' in i: ir=i['cm_array'] 
00153     else: 
00154        # FGG: in original cM I was adding everything from CMD to the entry
00155        # but at the end it was too messy, so we only add to entry from cm_array now
00156        #ir=i
00157        ir={}
00158        if i.get('path_type','')!='': ir['path_type']=i['path_type']
00159        if i.get('path','')!='': ir['path']=i['path']
00160 
00161     # Load data to get path
00162     ii={}
00163     ii['cm_run_module_uoa']=ini['cfg']['cm_modules']['cm-core']
00164     ii['cm_action']='load'
00165     if 'cm_module_uoa' in i: ii['cm_module_uoa']=i['cm_module_uoa']
00166     if 'cm_data_uoa' in i: ii['cm_data_uoa']=i['cm_data_uoa']
00167     if 'cm_repo_uoa' in i: ii['cm_repo_uoa']=i['cm_repo_uoa']
00168     rx=cm_kernel.access(ii)
00169     if rx['cm_return']>0: return rx
00170 
00171     ii={};ii.update(i)
00172     ii['cm_run_module_uoa']=ini['cfg']['cm_modules']['cm-core']
00173     ii['cm_console']=''
00174     if cm_kernel.ini.get('cm_console','')!='web': ii['cm_console']=i.get('cm_console','')
00175     if cm_kernel.ini.get('web','')=='yes': ii['cm_report_in_html']='yes'
00176 
00177     ii['cm_array']=ir
00178 
00179     ru=cm_kernel.access(ii)
00180     if ru['cm_return']>0: return ru
00181 
00182     # We need it here since this function overloads original 'core' update_data function
00183     ru['cm_skip_report']='yes'
00184 
00185     return ru
00186 
00187 # ============================================================================
00188 def find_path_to_repository(i):
00189 
00190     """
00191     Find path to a given repository
00192 
00193     Input:  {
00194               (find_repo_uoa)     - repo UOA
00195               (get_default_repo)  - if 'yes' and find_repo_uoa=='', get path to default repo
00196               (cm_console)        - if 'txt', output as text to console
00197               (cm_admin)          - if 'yes', override access control - only internal use,
00198                                     can not be used during web access (explicitly removed)
00199             }
00200 
00201     Output: {
00202               cm_return        - return code >0 if error
00203               cm_path          - path to repository
00204               cm_data_obj      - cM data object
00205               cm_uid           - uid (from UOA)
00206               cm_alias         - alias (from UOA)
00207               cm_uoa           - cm_data_uoa (alias or uid if alias=='')
00208               (cur_module_uoa) - current module UOA if in current path
00209               (cur_data_uoa)   - current data UOA if in current path
00210             }
00211     """
00212 
00213     p=''
00214 
00215     find_repo_uoa=''
00216 
00217     # If repository is not given, check current, local and then default repositories
00218     cur_info={}
00219 
00220     if 'find_repo_uoa' in i and i['find_repo_uoa']!='':
00221        find_repo_uoa=i['find_repo_uoa']
00222     else:
00223        er=False
00224 
00225        if i.get('get_default_repo','')!='yes':
00226           r=cm_kernel.find_path_to_current_repository({})
00227           if r['cm_return']>0: return r
00228           elif r['cm_return']==0:
00229              p=r['cm_path']
00230              if r.get('cm_module_uoa','')!='': cur_info['cur_module_uoa']=r['cm_module_uoa']
00231              if r.get('cm_data_uoa','')!='': cur_info['cur_data_uoa']=r['cm_data_uoa']
00232           else:
00233              er=True
00234 
00235        if er or i.get('get_default_repo','')=='yes':
00236           if 'cm_local_repo' in cm_kernel.ini and os.path.isdir(cm_kernel.ini['cm_local_repo']):
00237              p=cm_kernel.ini['cm_local_repo']
00238           elif 'cm_default_repo' in cm_kernel.ini and os.path.isdir(cm_kernel.ini['cm_default_repo']):
00239              p=cm_kernel.ini['cm_default_repo']
00240           else:
00241              return {'cm_return':0, 'cm_error':'can\'t find repository'}
00242 
00243        # Check uid of this repository
00244        r1=get_all_repo_paths({})
00245        if r1['cm_return']>0: return r1
00246 
00247        found=False
00248        for x in r1['cm_array']:
00249            if os.path.isdir(p) and os.path.isdir(x['cm_path']) \
00250               and os.stat(p)==os.stat(x['cm_path']):
00251               found=True
00252               break
00253 
00254        if not found:
00255           return {'cm_return':1, 'cm_error': 'access is likely forbidden to repo '+p}
00256 
00257        find_repo_uoa=x['cm_uid']
00258 
00259     # Try to load repository to check various parameters ...
00260     ii={'cm_action':'load',
00261         'cm_run_module_uoa':ini['cm_module_uid'],
00262         'cm_data_uoa':find_repo_uoa,
00263         'cm_admin':i.get('cm_admin','')}
00264     r=cm_kernel.access(ii)
00265     if r['cm_return']>0: return r
00266 
00267     d=r['cm_data_obj']
00268     uid=r['cm_uid']
00269     uoa=r['cm_uoa']
00270     alias=r['cm_alias']
00271 
00272     # If  remote 
00273     p=''
00274     if d['cfg'].get('path_type','')=='remote_url':
00275        p='#remote_url#'
00276     else:
00277        # Prepare path 
00278        r2=prepare_path({'cm_cfg':r['cm_data_obj']['cfg']})
00279        if r2['cm_return']>0: return r2
00280        p=r2['cm_path']
00281 
00282        if not os.path.exists(p):
00283           try:
00284              os.makedirs(p)
00285           except Exception as e:
00286              pass
00287 
00288     r['cm_path']=p
00289 
00290     if i.get('cm_console','')=='txt':
00291        cm_kernel.print_for_con(p)
00292 
00293     r.update(cur_info)
00294 
00295     return r
00296 
00297 # ============================================================================
00298 def test_repository(i):
00299 
00300     """
00301     Test repository (mainly remote access)
00302     It just try to load tmp:tmp and returns ok, if it exists or not found,
00303     thus meaning that the structure of repository/access is fine
00304 
00305     Input:  {
00306               test_repo_uoa - repo UOA
00307 
00308               ...           - various additional parameters 
00309                               (for example, for authentication)
00310             }
00311 
00312     Output: {
00313               cm_return     - return code >0 if error
00314             }
00315     """
00316 
00317     repo=i.get('test_repo_uoa','')
00318     if repo=='':
00319        return {'cm_return':1, 'cm_error':'"test_repo_uoa" is not specified'}
00320 
00321     con=i.get('cm_console','')
00322 
00323     # First try to load repository 
00324     ii={'cm_action':'load',
00325         'cm_run_module_uoa':ini['cm_module_uid'],
00326         'cm_data_uoa':repo}
00327     r=cm_kernel.access(ii)
00328     if r['cm_return']>0: return r
00329 
00330     # Try to load some data from the repository
00331     i['cm_action']='load'
00332     i['cm_run_module_uoa']=ini['cfg']['cm_modules']['cm-module']
00333     i['cm_console']='json'
00334     if 'cm_module_uoa' in i: del(i['cm_module_uoa'])
00335     i['cm_data_uoa']='tmp'
00336 
00337     if repo!='': 
00338        i['cm_repo_uoa']=repo
00339        del(i['test_repo_uoa'])
00340     r=cm_kernel.access(i)
00341     if r['cm_return']>0 and r['cm_return']!=16: return r
00342 
00343     if con=='txt':
00344        cm_kernel.print_for_con('Ok')
00345 
00346     return {'cm_return':0}
00347 
00348 # ============================================================================
00349 def get_all_repo_paths(i):
00350 
00351     """
00352     Get paths for all repositories (has to be low level operation!)
00353 
00354     Input:  {
00355               (cm_admin)          - if 'yes', override access control - only internal use,
00356                                     can not be used during web access (explicitly removed)
00357             }
00358 
00359     Output: {
00360               cm_return  - return code >0 if error
00361               cm_array   - array with paths
00362             }
00363     """
00364 
00365     # Get repositories where to search for 'repo' - has to be here!!!
00366     r=cm_kernel.find_path_to_work_repositories({})
00367     if r['cm_return']>0: return r
00368     a=r['cm_array']
00369     b=[]
00370 
00371     # Look through all repo UIDs
00372     r1={'cm_module_uoa':ini['cm_module_uid']}
00373     # 'cm_only_uid':'yes'}
00374     for x in a:
00375         r1['cm_path']=x
00376         r1['cm_admin']=i.get('cm_admin','')
00377         # Obtain list of data from the repository
00378         r=cm_kernel.get_all_uoa(r1)
00379         if r['cm_return']==0:
00380            for y in r['cm_array']:
00381                r1['cm_data_uoa']=y
00382                r1['cm_admin']=i.get('cm_admin','')
00383                r=cm_kernel.load_data(r1)
00384                if r['cm_return']==0:
00385                   r2=prepare_path({'cm_cfg':r['cm_data_obj']['cfg']})
00386                   if r2['cm_return']>0: return r2
00387 
00388                   p=r2['cm_path']
00389                   p1=r2['cm_path_without_cmr']
00390                   if p!='' and p!=cm_kernel.ini['dcfg']['cmr_ext']:
00391                      found=False
00392                      for q in b:
00393                          if os.path.isdir(q['cm_path']) and os.path.isdir(p) and os.stat(q['cm_path'])==os.stat(p):
00394                             found=True
00395                             break
00396                      if not found: 
00397                         b.append({'cm_path':p,
00398                                   'cm_path_without_cmr':p1,
00399                                   'cm_uoa':r1['cm_data_uoa'],
00400                                   'cm_uid':r['cm_uid'],
00401                                   'cm_alias':r['cm_alias']})
00402 
00403     if i.get('cm_console','')=='txt':
00404        for x in b:
00405            cm_kernel.print_for_con(x['cm_path'])
00406 
00407     return {'cm_return':0, 'cm_array':b}
00408 
00409 # ============================================================================
00410 def prepare_path(i):
00411 
00412     """
00413     Prepare path from the repository entry as absolute path 
00414     (convert from relative or absolute)
00415 
00416     Input:  {
00417               cm_cfg              - cfg file of the repository
00418             }
00419 
00420     Output: {
00421               cm_return           - return code >0 if error
00422               cm_path             - path
00423               cm_path_without_cmr - path without .cmr
00424             }
00425     """
00426 
00427     z=i['cm_cfg']
00428     p=''
00429     p1=''
00430 
00431     if 'path_type' in z:
00432        if z['path_type']=='relative_to_cm':
00433           p1=os.path.normpath(os.path.join(cm_kernel.ini[cm_kernel.env_cm_root], z['path']))
00434        elif z['path_type']=='absolute':
00435           p1=os.path.normpath(z['path'])
00436        p=os.path.normpath(os.path.join(p1, cm_kernel.ini['dcfg']['cmr_ext']))
00437 
00438     return {'cm_return':0, 'cm_path':p, 'cm_path_without_cmr':p1}
00439 
00440 # ============================================================================
00441 def share(i):
00442 
00443     """
00444     Check out repository if it is shared
00445 
00446     Input:  {
00447               cm_command    - explicit command for sharing tool 'co' or 'commit'
00448               (cm_repo_uoa) - repository UOA; if empty, update all repositories that are shared
00449             }                
00450     Output: {
00451               cm_return  - return code >0 if error
00452             }
00453     """
00454 
00455     # Check some vars
00456     cx=i.get('cm_command','')
00457     if cx=='': return {'cm_return':1, 'cm_error':'command is not specified in "repo/share"'}
00458 
00459     # Build list of repos if needed
00460     repos=[]
00461 
00462     if i.get('cm_repo_uoa','')=='':
00463        jj={}
00464        jj['cm_run_module_uoa']=ini['cm_module_uid']
00465        jj['cm_action']='list'
00466        rr=cm_kernel.access(jj)
00467        if rr['cm_return']>0: return rr
00468 
00469        for xx in rr['cm_mixed']:
00470            x=xx['cm_uoa'];  xu=xx['cm_uid'];  xa=xx['cm_alias'];  xd=xx['cm_display_html']
00471 
00472            r=find_path_to_repository({'find_repo_uoa':xu})
00473            if r['cm_return']==0:
00474               repos.append({'uoa':r['cm_uoa'], 'display':r['cm_display_as_alias'], 'cfg':r['cm_data_obj']['cfg'], 'path':r['cm_path']})
00475     else:
00476        r=find_path_to_repository({'find_repo_uoa':i['cm_repo_uoa']})
00477        if r['cm_return']>0: return r
00478 
00479        repos.append({'uoa':r['cm_uoa'], 'display':r['cm_display_as_alias'], 'cfg':r['cm_data_obj']['cfg'], 'path':r['cm_path']})
00480 
00481     # go through repositories
00482     for q in repos:
00483        d=q['cfg']
00484        p=q['path']
00485 
00486        if d.get('share','')!='yes':
00487           if i.get('cm_repo_uoa','')!='': return {'cm_return':1, 'cm_error':'this repository is not shared'}
00488           else: continue
00489 
00490        if i.get('cm_repo_uoa','')=='': cm_kernel.print_for_con('************************************************************')
00491        else:                           cm_kernel.print_for_con('')
00492        x='Updating '
00493        if q['display']!='': x+=q['display']
00494        else: x+=q['uoa']
00495 
00496        cm_kernel.print_for_con(x)
00497        cm_kernel.print_for_con('')
00498 
00499        if 'sharing_tool' not in d:
00500           if i.get('cm_repo_uoa','')!='': return {'cm_return':1, 'cm_error':'"sharing_tool" is not specified for this repository'}
00501           else: continue
00502           
00503        if d['sharing_tool'] not in ini['cfg']['sharing_tools']:
00504           if i.get('cm_repo_uoa','')!='': return {'cm_return':1, 'cm_error':'"sharing_tool" is unknown for this repository'}
00505           else: continue
00506 
00507        command=ini['cfg']['sharing_tools'][d['sharing_tool']][cx]
00508        command1=command.replace(cm_kernel.convert_str_to_special('sharing_url'), d['sharing_url'])
00509        command2=command1.replace(cm_kernel.convert_str_to_special('cm_path'), p)
00510 
00511        cm_kernel.print_for_con('Executing '+command2+' ...')
00512        cm_kernel.print_for_con('')
00513 
00514        r=os.system(command2)
00515        if r>0:
00516           if i.get('cm_repo_uoa','')!='': return {'cm_return':1, 'cm_error':'exit code '+str(r)}
00517           else: 
00518              cm_kernel.print_for_con('')
00519              cm_kernel.print_for_con('Repository update likely failed - exit code: '+str(r))
00520              cm_kernel.print_for_con('')
00521              var=raw_input('Press enter to continue: ')
00522              cm_kernel.print_for_con('')
00523 
00524     cm_kernel.print_for_con('')
00525     cm_kernel.print_for_con('Updating finished!')
00526 
00527     return {'cm_return':0}
00528 
00529 # ============================================================================
00530 def download(i):
00531 
00532     """
00533     Download repository using cM web interface (possibly substitute old entries)
00534 
00535     Input:  {
00536               (web_repo_uoa)        - repository UOA; if empty, update all repositories that are shared
00537               (overwrite)           - if 'yes', overwrite entries
00538               (download_all)        - if 'yes', download all
00539               (skip_large_download) - if 'yes', skip entries with large downloads
00540               (interactive)         - if 'yes', interactive
00541               (ask)                 - if 'yes', ask what to do with modules with many entries
00542               (cm_remote_user_uoa)  - change default user to access repo ...
00543             }                
00544     Output: {
00545               cm_return  - return code >0 if error
00546             }
00547     """
00548 
00549     ow=i.get('overwrite','')
00550     cru=i.get('cm_remote_user_uoa','')
00551 
00552     cm_kernel.print_for_con('Warning: currently it can be a very long operation')
00553     cm_kernel.print_for_con('         and we hope to speed it up in the future - please, be patient!')
00554     cm_kernel.print_for_con('')
00555 
00556     # Start timer
00557     t0=time.time()
00558 
00559     # Search through repositories
00560     rlist=[]
00561     if i.get('web_repo_uoa','')!='':
00562        # Load repo
00563        r2=cm_kernel.access({'cm_run_module_uoa':ini['cm_module_uid'],
00564                             'cm_action':'load',
00565                             'cm_data_uoa':i['web_repo_uoa']})
00566        if r2['cm_return']>0: return r2
00567        rlist=[{'cm_uoa':r2['cm_uoa'], 'cm_uid':r2['cm_uid']}]
00568     else:
00569        r2=cm_kernel.access({'cm_run_module_uoa':ini['cm_module_uid'],
00570                             'cm_action':'list'})
00571        if r2['cm_return']>0: return r2
00572        rlist=r2['cm_mixed']
00573 
00574     for repo1 in rlist:
00575         # Check print
00576         repo_uoa=repo1['cm_uoa']
00577         repo_uid=repo1['cm_uid']
00578 
00579         ww=repo_uoa
00580 
00581         # Load repo
00582         ii={}
00583         ii['cm_run_module_uoa']=ini['cm_module_uid']
00584         ii['cm_action']='load'
00585         ii['cm_data_uoa']=ww
00586         rr=cm_kernel.access(ii)
00587         if rr['cm_return']>0 and rr['cm_return']!=16: return rr
00588         if rr['cm_return']==0:
00589            d=rr['cm_data_obj']['cfg']
00590 
00591            wru=d.get('web_repo_uoa','')
00592            rru=d.get('remote_repo_uoa','')
00593 
00594            # Check repository that supports downloading
00595            if wru!='' and rru!='':
00596               cm_kernel.print_for_con('============================================================')
00597               cm_kernel.print_for_con('Processing repository '+ww+' ...')
00598 
00599               ii={}
00600               ii['cm_run_module_uoa']=ini['cfg']['cm_modules']['cm-core']
00601               ii['cm_action']='list'
00602               ii['cm_repo_uoa']=wru
00603               ii['remote_repo_uoa']=rru
00604               ii['cm_only_available_modules']='yes'
00605               if cru!='': ii['cm_remote_user_uoa']=cru
00606               r1=cm_kernel.access(ii)
00607               if r1['cm_return']==0:
00608 
00609                  # Iterating over available modules in the repo
00610                  for q in sorted(r1['cm_mixed'], key=lambda k: k['cm_uoa']):
00611                      q1=q['cm_uid']
00612                      q2=q['cm_display_as_alias']
00613                      q3=q['cm_uoa']
00614                      cm_kernel.print_for_con('************************************************************')
00615                      cm_kernel.print_for_con('Retrieving entries for module "'+q3+'":')
00616 
00617                      # Load module
00618                      ii={}
00619                      ii['cm_run_module_uoa']=ini['cfg']['cm_modules']['cm-module']
00620                      ii['cm_action']='load'
00621                      ii['cm_data_uoa']=q1
00622                      rr=cm_kernel.access(ii)
00623                      if rr['cm_return']>0: return rr
00624                      dm=rr['cm_data_obj']['cfg']
00625 
00626                      # List data entries
00627                      jj={}
00628                      jj['cm_run_module_uoa']=ini['cfg']['cm_modules']['cm-core']
00629                      jj['cm_action']='list'
00630                      jj['cm_module_uoa']=q['cm_uid']
00631                      jj['cm_repo_uoa']=wru
00632                      jj['remote_repo_uoa']=rru
00633                      jj['skip_data_cfg']='yes'
00634 
00635                      s='M' # minimal download by default
00636 
00637                      if i.get('download_all','')=='yes':          s='A'
00638                      elif i.get('skip_large_download','')=='yes': s='S'
00639                      elif i.get('interactive','')=='yes':         s='I'
00640                      elif i.get('ask','')=='yes':                 s=''
00641 
00642                      if cru!='': jj['cm_remote_user_uoa']=cru
00643 
00644                      all=[]
00645 
00646                      # Check if module have "minimal setup" to prune downloads
00647                      if dm.get('minimal_setup_for_download','')=='yes':
00648                         if s=='':
00649                            cm_kernel.print_for_con('')
00650                            cm_kernel.print_for_con('NOTE: there may be many entries associated with this module!')
00651                            cm_kernel.print_for_con('      Press <Enter>  to download only minimal set (default)')
00652                            cm_kernel.print_for_con('            A<Enter> to download all entries')
00653                            cm_kernel.print_for_con('            I<Enter> to download interactively entries')
00654                            cm_kernel.print_for_con('            S<Enter> to skip this module')
00655                            s=raw_input('')
00656 
00657                         if s=='s' or s=='S':
00658                            continue
00659                         elif s=='' or s=='m' or s=='M':
00660                            # adding setup.minimal class for listing
00661                            jj['cm_classes_uoa']=ini['cfg']['class_setup_minimal_uoa']
00662 
00663                      jj_copy=xcopy.deepcopy(jj)
00664                      r2=cm_kernel.access(jj)
00665                      if r2['cm_return']>0: return r2
00666                      for q in r2['cm_mixed']:
00667                          all.append(q)
00668 
00669                      if s=='' or s=='m' or s=='M':
00670                         # adding setup.minimal class for listing
00671                         jj=jj_copy
00672                         jj['cm_classes_uoa']=ini['cfg']['class_setup_minimal1_uoa']
00673 
00674                         r2=cm_kernel.access(jj)
00675                         if r2['cm_return']>0: return r2
00676                         for q in r2['cm_mixed']:
00677                             all.append(q)
00678                       
00679                      cm_kernel.print_for_con('')
00680                      for k in sorted(all, key=lambda k: k['cm_uoa']):
00681                          k1=k['cm_uid']
00682                          k2=k['cm_display_as_alias']
00683                          k3=k['cm_uoa']
00684 
00685                          download=True
00686                          if s=='I' or s=='i':
00687                             x=raw_input('Would you like to download cM entry "'+q3+':'+k3+'" (Y/N(default)):')
00688                             if x=='N' or x=='n' or x=='': download=False
00689                             
00690                          if download:
00691                             cm_kernel.print_for_con('')
00692                             cm_kernel.print_for_con('Downloading cM entry "'+q3+':'+k3+'" (elapsed time='+str("%.1f" % (time.time()-t0))+' sec.) ...')
00693 
00694                             # Check if already exists
00695                             exists=True
00696                             jj={}
00697                             jj['cm_run_module_uoa']=ini['cfg']['cm_modules']['cm-core']
00698                             jj['cm_action']='load'
00699                             jj['cm_module_uoa']=q3
00700                             jj['cm_data_uoa']=k3
00701                             jj['cm_repo_uoa']=ww
00702                             if cru!='': ii['cm_remote_user_uoa']=cru
00703                             r2=cm_kernel.access(jj)
00704                             if r2['cm_return']>0: 
00705                                if r2['cm_return']!=16: return r2
00706                                exists=False
00707 
00708                             path=''
00709 
00710                             # Individually check a few modules (should move to cfg)
00711                             if exists: 
00712                                path=r2['cm_path']
00713                             else:
00714                                # Create local entry
00715                                jj={}
00716                                jj['cm_run_module_uoa']=ini['cfg']['cm_modules']['cm-core']
00717                                jj['cm_action']='add'
00718                                jj['cm_module_uoa']=q3
00719                                jj['cm_data_uoa']=k3
00720                                jj['cm_data_uid']=k1
00721                                jj['cm_repo_uoa']=ww
00722                                r2=cm_kernel.access(jj)
00723                                if r2['cm_return']>0: return r2
00724                                path=r2['cm_path']
00725 
00726                             if not exists or ow=='yes':
00727                                if exists and ow!='yes':
00728                                   cm_kernel.print_for_con('   Entry exists and overwrite mode is off - skipping ...')
00729 
00730                                # Get data description
00731                                jj={"cm_action":"load",
00732                                    "cm_run_module_uoa":ini['cfg']['cm_modules']['cm-core'],
00733                                    "cm_module_uoa":q3,
00734                                    "cm_data_uoa":k3,
00735                                    "cm_repo_uoa":wru,
00736                                    "remote_repo_uoa":rru}
00737                                if cru!='': jj['cm_remote_user_uoa']=cru
00738                                r2=cm_kernel.access(jj)
00739                                if r2['cm_return']>0: return r2
00740                                dd=r2['cm_data_obj']['cfg']
00741 
00742                                # Get list of files
00743                                jj={"cm_action":"get_list_of_all_files",
00744                                    "cm_run_module_uoa":ini['cfg']['cm_modules']['cm-core'],
00745                                    "cm_module_uoa":q3,
00746                                    "cm_data_uoa":k3,
00747                                    "cm_repo_uoa":wru,
00748                                    "remote_repo_uoa":rru}
00749                                if cru!='': jj['cm_remote_user_uoa']=cru
00750                                r2=cm_kernel.access(jj)
00751                                if r2['cm_return']>0: return r2
00752 
00753                                lf=r2['cm_array']
00754                                if len(lf)>6:
00755                                   cm_kernel.print_for_con('   Downloading archive ...')
00756                                   # If many files, pack entry before downloading
00757                                   fn=os.path.join(path, 'downloaded.zip')
00758 
00759                                   # Download
00760                                   jj={"cm_action":"download",
00761                                       "cm_run_module_uoa":ini['cfg']['cm_modules']['cm-core'],
00762                                       "cm_module_uoa":q3,
00763                                       "cm_data_uoa":k3,
00764                                       "cm_repo_uoa":wru,
00765                                       "remote_repo_uoa":rru,
00766                                       "cm_save_to_file":fn,
00767                                       "cm_all_files":"yes"}
00768                                   if cru!='': jj['cm_remote_user_uoa']=cru
00769                                   r2=cm_kernel.access(jj)
00770                                   if r2['cm_return']>0: return r2
00771 
00772                                   cm_kernel.print_for_con('   Unpacking (archive size='+str(os.path.getsize(fn))+' bytes) ...')
00773 
00774                                   # Unzip
00775                                   f=open(fn,'rb')
00776                                   z=zipfile.ZipFile(f)
00777                                   for d in z.namelist():
00778                                       if os.sep!='/': 
00779                                          d=d.replace('/', os.sep)
00780 
00781                                       if not d.startswith('..') and not d.startswith('/') and not d.startswith('\\'):
00782                                          dr=os.path.dirname(d)
00783                                          pp2=os.path.normpath(os.path.join(path,d))
00784                                          if d.endswith('/') or d.endswith('\\'): 
00785                                             # create directory 
00786                                             if not os.path.exists(pp2): os.makedirs(pp2)
00787                                          else:
00788                                             # check subdirectory
00789                                             if dr!='':
00790                                                dr1=os.path.join(path,dr)
00791                                                if not os.path.exists(dr1): os.makedirs(dr1)
00792                                             # extract file
00793                                             fine=True
00794                                             if os.path.exists(pp2):
00795                                                if ow=='yes':
00796                                                   # check if overwrite
00797                                                   os.remove(pp2)
00798                                                else:
00799                                                   fine=False
00800 
00801                                             if fine:
00802                                                fo=open(pp2, 'wb')
00803                                                fo.write(z.read(d))
00804                                                fo.close()
00805                                   f.close()
00806                                   os.remove(fn)   
00807                                else:
00808                                   # Overwrite data.json directly
00809                                   r4=cm_kernel.save_array_to_file_as_json({'cm_filename':os.path.join(path,cm_kernel.var_cm_info,cm_kernel.var_cm_data), \
00810                                                                            'cm_array':dd})
00811                                   if r4['cm_return']>0: return r4
00812                                   
00813                                   # If just a few files, download directly
00814                                   for q in lf:
00815                                       ql=q
00816                                       if os.sep!='/': 
00817                                          ql=q.replace('/', os.sep)
00818 
00819                                       cm_kernel.print_for_con('   Downloading file '+ql+' ...')
00820 
00821                                       dr=os.path.join(path,ql)
00822                                       # Check if sub-directory
00823                                       path, filename = os.path.split(dr)
00824                                       if not os.path.exists(path): 
00825                                          os.makedirs(path)
00826 
00827                                       # Download
00828                                       jj={"cm_action":"show",
00829                                           "cm_run_module_uoa":ini['cfg']['cm_modules']['cm-core'],
00830                                           "cm_module_uoa":q3,
00831                                           "cm_data_uoa":k3,
00832                                           "cm_repo_uoa":wru,
00833                                           "remote_repo_uoa":rru,
00834                                           "cm_web_filename":q,
00835                                           "cm_save_to_file":dr,
00836                                           "cm_web_content":"unknown"}
00837                                       if cru!='': jj['cm_remote_user_uoa']=cru
00838                                       r2=cm_kernel.access(jj)
00839                                       if r2['cm_return']>0: return r2
00840 
00841                                # Update local entry (for indexing)
00842                                jj={}
00843                                jj['cm_run_module_uoa']=ini['cfg']['cm_modules']['cm-core']
00844                                jj['cm_action']='update'
00845                                jj['cm_module_uoa']=q3
00846                                jj['cm_data_uoa']=k1
00847                                jj['cm_repo_uoa']=ww
00848                                jj['cm_array']={}
00849                                jj['cm_skip_update_info']='yes'
00850                                r2=cm_kernel.access(jj)
00851                                if r2['cm_return']>0: return r2
00852                             else:
00853                                cm_kernel.print_for_con('   Entry exists and overwrite mode is off - skipping ...')
00854 
00855     return {'cm_return':0}
00856 
00857 # ============================================================================
00858 def web_copy(i):
00859 
00860     """
00861     Copy repository to another one (and clean target if needed)
00862 
00863     Input:  {
00864             }
00865 
00866     Output: {
00867               cm_return  - return code >0 if error
00868               cm_path    - path to file
00869               cm_uid     - generated uid
00870             }
00871     """
00872 
00873     # Get web style
00874     if 'cfg' in cm_kernel.ini['web_style']: web=cm_kernel.ini['web_style']['cfg']
00875     else:
00876        return {'cm_return':1, 'cm_error':'web style is not defined'}
00877 
00878     cm_kernel.print_for_con('<span class="cm-title">Copy repository</span><br>')
00879 
00880     # Detecting/restoring data from forms
00881     a1={}
00882     r=cm_kernel.access({'cm_run_module_uoa':ini['cfg']['cm_modules']['cm-web'],
00883                         'cm_action':'detect_form_params',
00884                         'cm_array':i, 
00885                         'cm_prefix':'#form1'})
00886     if r['cm_return']>0: return r
00887     cm_form_array1=r['cm_array']
00888     cm_form_commands1=r['cm_commands']
00889 
00890     # Get data description for this action
00891     r=cm_kernel.get_data_description({'cm_module_uoa':ini['cm_module_uoa'], 
00892                                       'cm_which_action':i['cm_action']})
00893     if r['cm_return']>0: return r
00894     cm_data_desc1=r['cm_data_desc']
00895     cm_params_default1=r['cm_params_default']
00896 
00897     # Check default
00898     forms_exists='yes'
00899     if len(cm_form_array1)==0:
00900        a1=cm_params_default1
00901 
00902        forms_exists='no'
00903     else:
00904        r=cm_kernel.restore_flattened_array({'cm_array':cm_form_array1, 
00905                                             'cm_replace_in_keys':{'^35^':'#', '^64^':'@'}})
00906        if r['cm_return']>0: return r
00907        a1=r['cm_array']
00908 
00909     # Check if clean
00910     if 'cm_submit_copy' in i:
00911        ii={}
00912        ii['cm_run_module_uoa']=ini['cm_module_uid']
00913        ii['cm_action']='copy'
00914 
00915        ii['cm_detach_console']='yes'
00916 
00917        ii.update(a1)
00918 
00919        r=cm_kernel.access_fe_through_cmd(ii)
00920        if r['cm_return']>0: return r
00921 
00922        x='Check detached console for progress!'
00923        if r.get('cm_stdout','')!='': x=r['cm_stdout']
00924        cm_kernel.print_for_con('<BR>' )
00925        cm_kernel.print_for_con(x)
00926        cm_kernel.print_for_con('<BR><BR>' )
00927 
00928     else:
00929        cm_kernel.print_for_con('<FORM ACTION="" name="add_edit" METHOD="POST" enctype="multipart/form-data" accept-charset="utf-8">' )
00930 
00931        ii={'cm_run_module_uoa':ini['cfg']['cm_modules']['cm-web'],
00932            'cm_action':'visualize_data',
00933            'cm_array':a1,
00934            'cm_data_desc':cm_data_desc1,
00935            'cm_form_commands':cm_form_commands1,
00936            'cm_separator':'#',
00937            'cm_separator_form':'#form1#',
00938            'cm_forms_exists':forms_exists,
00939            'cm_support_raw_edit':'no',
00940            'cm_mode':'add'}
00941        if 'cm_raw_edit' in i: ii['cm_raw_edit']=i['cm_raw_edit']
00942        if 'cm_back_json' in i: ii['cm_back_json']=i['cm_back_json']
00943        r=cm_kernel.access(ii)
00944        if r['cm_return']>0: return r
00945        cm_kernel.print_for_web(r['cm_string'])
00946 
00947        cm_kernel.print_for_con('<input type="submit" class="cm-button" name="cm_submit_copy" value="(Clean and) Copy">')
00948 
00949        cm_kernel.print_for_con('</FORM><br>')
00950 
00951     return {'cm_return':0}
00952 
00953 # ============================================================================
00954 def copy(i):
00955 
00956     """
00957     Copy repository to another one (and clean target if needed)
00958 
00959     Input:  {
00960               orig_repo_uoa       - original repository
00961               (orig_module_uoa)   - copy data for this module
00962               (cm_classes_uoa)    - prune data by classes
00963 
00964               target_repo_uoa     - target repository
00965               (clean_target_repo) - force cleaning of target repo
00966             }
00967 
00968     Output: {
00969               cm_return  - return code >0 if error
00970               cm_path    - path to file
00971               cm_uid     - generated uid
00972             }
00973     """
00974 
00975     # Check some vars
00976     trepo=i.get('target_repo_uoa','')
00977     if trepo=='': return {'cm_return':1,'cm_error':'parameter "target_repo_uoa" is not set in repo/copy'}
00978 
00979     orepo=i.get('orig_repo_uoa','')
00980     omodule=i.get('orig_module_uoa','')
00981 
00982     # Check if need cleaning of target repository
00983     if i.get('clean_target_repo','')=='yes':
00984        r=clean({'target_repo_uoa':i['target_repo_uoa'], 
00985                 'target_module_uoa':i.get('orig_module_uoa',''),
00986                 'target_data_uoa':i.get('orig_data_uoa',''),
00987                 'cm_classes_uoa':i.get('cm_classes_uoa',[])})
00988        if r['cm_return']>0: return r
00989 
00990     cm_kernel.print_for_con('************************************************************')
00991     cm_kernel.print_for_con('Copying repository ...')
00992     cm_kernel.print_for_con('')
00993 
00994     # Copying data
00995     ii={'cm_run_module_uoa':ini['cfg']['cm_modules']['cm-core'], 
00996         'cm_action':'list'}
00997     if orepo!='': ii['cm_repo_uoa']=orepo
00998     if omodule!='': ii['cm_module_uoa']=omodule
00999     if i.get('orig_data_uoa','')!='': ii['prune_data_uoa']=i['orig_data_uoa']
01000     if len(i.get('cm_classes_uoa',[]))>0: ii['cm_classes_uoa']=i['cm_classes_uoa']
01001 
01002     r=cm_kernel.access(ii)
01003     if r['cm_return']>0: return r
01004 
01005     for xx in r['cm_mixed']:
01006         x=xx['cm_uoa'];  xu=xx['cm_uid'];  xa=xx['cm_alias'];  xd=xx['cm_display_html']
01007 
01008         cm_kernel.print_for_con('  Copying '+xx['cm_module_uoa']+':'+x+' ...')
01009         
01010         ii={'cm_run_module_uoa':ini['cfg']['cm_modules']['cm-core'],
01011             'cm_action':'copy',
01012             'orig_module_uoa':xx['cm_module_uid'],
01013             'orig_data_uoa':xu,
01014             'target_repo_uoa':trepo}
01015         if orepo!='': ii['orig_repo_uoa']=orepo
01016 
01017         r=cm_kernel.access(ii)
01018         if r['cm_return']>0: 
01019            cm_kernel.print_for_con('    Error copying data: '+r['cm_error'])
01020 
01021     cm_kernel.print_for_con('')
01022     cm_kernel.print_for_con('Copying finished!')
01023 
01024     return {'cm_return':0}
01025 
01026 # ============================================================================
01027 def clean(i):
01028 
01029     """
01030     Clean repository 
01031 
01032     Input:  {
01033               target_repo_uoa     - target repo UOA
01034               (target_module_uoa) - clean data for this module
01035               (cm_classes_uoa)    - prune data by classes
01036               (target_data_uoa)   - data to clean
01037           
01038             }
01039 
01040     Output: {
01041               cm_return  - return code >0 if error
01042               cm_path    - path to file
01043               cm_uid     - generated uid
01044             }
01045     """
01046 
01047     cm_kernel.print_for_con('************************************************************')
01048     cm_kernel.print_for_con('Cleaning repository ...')
01049     cm_kernel.print_for_con('')
01050 
01051     # Check some vars
01052     trepo=i.get('target_repo_uoa','')
01053     if trepo=='': return {'cm_return':1,'cm_error':'parameter "target_repo_uoa" is not set in repo/clean'}
01054     tmodule=i.get('target_module_uoa','')
01055 
01056     # Get list of data:
01057     ii={'cm_run_module_uoa':ini['cfg']['cm_modules']['cm-core'], 
01058         'cm_action':'list',
01059         'cm_repo_uoa':trepo}
01060     if tmodule!='': ii['cm_module_uoa']=tmodule
01061     if i.get('target_data_uoa','')!='': ii['prune_data_uoa']=i['target_data_uoa']
01062     if len(i.get('cm_classes_uoa',[]))>0: ii['cm_classes_uoa']=i['cm_classes_uoa']
01063 
01064     r=cm_kernel.access(ii)
01065     if r['cm_return']>0: return r
01066 
01067     for xx in r['cm_mixed']:
01068         x=xx['cm_uoa'];  xu=xx['cm_uid'];  xa=xx['cm_alias'];  xd=xx['cm_display_html']
01069 
01070         cm_kernel.print_for_con('  Deleting '+xx['cm_module_uoa']+':'+x+' ...')
01071         
01072         ii={'cm_run_module_uoa':ini['cfg']['cm_modules']['cm-core'],
01073             'cm_action':'delete',
01074             'cm_repo_uoa':trepo,
01075             'cm_module_uoa':xx['cm_module_uid'],
01076             'cm_data_uoa':xu}
01077         r=cm_kernel.access(ii)
01078         if r['cm_return']>0: 
01079            cm_kernel.print_for_con('    Error deleting data: '+r['cm_error'])
01080 
01081     return {'cm_return':0}

Generated on Wed May 28 02:49:02 2014 for Collective Mind Framework by DoxyGen 1.6.1
Concept, design and coordination: Grigori Fursin (C) 1993-2013