
    tni=                     8   d Z ddlZddlZddlZddlmZ ddlZddlmZmZmZm	Z	 ddl
mZmZmZmZmZ ddlmZmZmZ ddlmZ dd	lmZ d
dlmZmZmZmZmZ ej                            ej                             e!          d          Z"d Z#	 	 	 ddZ$d Z%d Z&dS )z$
Runpod | CLI | Project | Functions
    N)datetime)commentdocumentnltable)__version__create_endpointcreate_templateget_podupdate_endpoint_template)BASE_DOCKER_IMAGEENV_VARS	GPU_TYPES)SSHConnection   )sync_directory   )attempt_pod_launchcopy_template_filesget_project_endpointget_project_podload_project_configstarter_templatesc                  `   t                      } t          d           d| d         d         i}| d                             di           D ]}| d         d         |         ||<   | d                             dg           }| d                             dd          r!|                    | d         d                    t	          | |          }|t          d	           dS t          d
d           t
          j                                         |                    dd          dk    s|                    d          Dt          |d                   }|                    dd          dk    /|                    d          D|d         }t          d| d         d          d| dd           |S )zLaunch a development pod.z&Deploying development pod on Runpod...RUNPOD_PROJECT_IDprojectuuidenv_vars	gpu_typesgpuNzHSelected GPU types unavailable, try again later or use a different type.z"Waiting for pod to come online...  )enddesiredStatusRUNNINGruntimeidzProject namez pod (z
) created.z

)	r   printgetappendr   sysstdoutflushr   )configenvironment_variablesvariableselected_gpu_typesnew_podproject_pod_ids         `/var/www/html/gpu-tools/venv/lib/python3.11/site-packages/runpod/cli/groups/project/functions.py_launch_dev_podr5   #   s    ""F	
2333 1&2CF2KL9%))*b99 R R*0*;J*G*Qh''  	*..{B??iUD)) <!!&"3E":;;; !)>??GV	
 	
 	
 t	
.B7777J 	OT**i77;;y!!)'$-(( 	OT**i77;;y!!) T]N	N6)$V,NNNNNN        Fc                 B
   |s.t           j                            t          j                    |           }t           j                            |          st          j        |           |d}t           j                            t          |          }t          ||           t           j                            |d          }	t          |	dd          5 }
|
	                                }ddd           n# 1 swxY w Y   dt          v r|                    dd	          }n|                    dd
t                     }t          |	dd          5 }
|
                    |           ddd           n# 1 swxY w Y   |rt           j                            | d          }t          |dd          5 }|	                                }|                    d|          }ddd           n# 1 swxY w Y   t          |dd          5 }|                    |           ddd           n# 1 swxY w Y   nt          j                    }t          t          j                              dd         }t!                      }|                    t%          d                     |                    t'                                 |                    d|            t)                      }|                    d|           |                    d|            |                    dt+          j        |                     |                    dt.                     |                    dd           |                    d|           |                    dd           |                    dd           |                    dd           |                    dt0                     |                    d |           t)                      }|                    d!t          |                     |                    d"t          |                     |                    d#|           t)                      }|                    d$|           |                    d%d           |                    d&d           |                    d'|           t          t           j                            |d(          dd)          5 }t3          j        ||           ddd           dS # 1 swxY w Y   dS )*zCreate a new project.Ndefaultzbuilder/requirements.txtrzutf-8)encodingdevz
<<RUNPOD>>z/git+https://github.com/runpod/runpod-python.gitzrunpod==wzsrc/handler.pyz<<MODEL_NAME>>   zRunpod Project Configurationtitler   r'   
base_image)cuda_versionr   	gpu_countr   
storage_idvolume_mount_pathz/runpod-volumeportsz8080/http, 22/tcpcontainer_disk_size_gb
   r   r   
model_type
model_nametemplatepython_versionhandler_pathrequirements_pathr%   zrunpod.tomlzUTF-8)ospathjoingetcwdexistsmakedirsSTARTER_TEMPLATESr   openreadr   replacewritestrr   uuid4r   addr   r   r   r   formatr   r   tomlkitdump)project_namerunpod_volume_idr@   rJ   rG   rH   init_current_dirproject_foldertemplate_dirrL   requirements_filerequirements_contentrK   filehandler_contentproject_uuidtoml_configproject_tabletemplate_tableruntime_tableconfig_files                        r4   create_new_projectrm   O   s     '%bikk<@@w~~n-- 	(K'''"Jw||$5zBBL.999 GLL9STT#S7;;; 	<?P#4#9#9#;#; 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< K#7#?#?O$ $   $8#?#?666$ $  #S7;;; 	:?P##$8999	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	:  	,7<<6FGGLlC'::: Xd"&))++"1"9"9:JJ"W"WX X X X X X X X X X X X X X X lC'::: ,d

?+++, , , , , , , , , , , , , , , tz||$$RaR(L**KOOG:;;<<<OOBDDOOG\***GGMfl+++fl+++l$5$<,$W$W$WXXXk9---k1%%%l$4555)+;<<<g2333.333j(+++OOI}---WWN|S__555|S__555OOJ///GGM&777n&6777)+EFFFOOI}---	
^]33S7
 
 
 /	[+.../ / / / / / / / / / / / / / / / / /sZ   C44C8;C8E11E58E50+G''G+.G+H&&H*-H*1TTTc                     t                      } | d         D ]#}t          d| d| d         |                     $t          d           t          | d         d                   }|st                      }|dS t	          |          5 }| d         d          d| d         d          }t
          j                            |d	          }t
          j                            |d
          }t
          j                            || d         d                   }t          d| d|            |                    d| d| g           t          d|            |	                    t          j
                    |           t
          j                            |d          }t          d| d|            d| d         d          d| d| d| d| d         d          g}	|                    |	           t          |t          j
                    |           | d         d         }
t
          j                            || d         d                   }t
          j                            || d         d                   }d| d| d|
 d| d| d | d!| d"g}t          d           t          d#           |                    |           ddd           dS # 1 swxY w Y   dS )$au  
    Start the project development environment from runpod.toml
    - Check if the project pod already exists.

    - If the project pod does not exist:
        # SSH into the pod and create a project folder within the volume
        # Create a folder in the volume for the project that matches the project uuid
        # Create a folder in the project folder that matches the project name
        # Copy the project files into the project folder
        # crate a virtual environment using the python version specified in the project config
        # install the requirements.txt file

    - If the project pod does exist:

    r   z    - z: r!   r   NrC   /r;   prodr'   zChecking pod project folder:  on pod 	mkdir -p  Syncing files to pod venv'Activating Python virtual environment: pythonr%   rJ   z -m virtualenv source /bin/activate &&cd P &&python -m pip install --upgrade pip &&python -m pip install -v --requirement rL   rK   ai  
            pkill inotify

            function force_kill {
                kill $1 2>/dev/null
                sleep 1

                if ps -p $1 > /dev/null; then
                    echo "Graceful kill failed, attempting SIGKILL..."
                    kill -9 $1 2>/dev/null
                    sleep 1

                    if ps -p $1 > /dev/null; then
                        echo "Failed to kill process with PID: $1"
                        exit 1
                    else
                        echo "Killed process with PID: $1 using SIGKILL"
                    fi

                else
                    echo "Killed process with PID: $1"
                fi
            }

            function cleanup {
                echo "Cleaning up..."
                force_kill $last_pid
            }

            trap cleanup EXIT SIGINT

            if source z/venv/bin/activate; then
                echo -e "- Activated virtual environment."
            else
                echo "Failed to activate virtual environment."
                exit 1
            fi

            if cd a  ; then
                echo -e "- Changed to project directory."
            else
                echo "Failed to change directory."
                exit 1
            fi

            exclude_pattern='(__pycache__|\.pyc$)'
            function update_exclude_pattern {
                exclude_pattern='(__pycache__|\.pyc$)'
                if [[ -f .runpodignore ]]; then
                    while IFS= read -r line; do
                        line=$(echo "$line" | tr -d '[:space:]')
                        [[ "$line" =~ ^#.*$ || -z "$line" ]] && continue # Skip comments and empty lines
                        exclude_pattern="${exclude_pattern}|(${line})"
                    done < .runpodignore
                    echo -e "- Ignoring files matching pattern: $exclude_pattern"
                fi
            }
            update_exclude_pattern

            # Start the API server in the background, and save the PID
            python a   --rp_serve_api --rp_api_host="0.0.0.0" --rp_api_port=8080 --rp_api_concurrency=1 &
            last_pid=$!

            echo -e "- Started API server with PID: $last_pid" && echo ""
            echo "Connect to the API server at:"
            echo ">  https://$RUNPOD_POD_ID-8080.proxy.runpod.net" && echo ""

            while true; do
                if changed_file=$(inotifywait -q -r -e modify,create,delete --exclude "$exclude_pattern" a   --format '%w%f'); then
                    echo "Detected changes in: $changed_file"
                else
                    echo "Failed to detect changes."
                    exit 1
                fi

                force_kill $last_pid

                if [[ $changed_file == *"requirements"* ]]; then
                    echo "Installing new requirements..."
                    python -m pip install --upgrade pip && python -m pip install -r z
                fi

                if [[ $changed_file == *".runpodignore"* ]]; then
                    update_exclude_pattern
                fi

                python z --rp_serve_api --rp_api_host="0.0.0.0" --rp_api_port=8080 --rp_api_concurrency=1 &
                last_pid=$!

                echo "Restarted API server with PID: $last_pid"
            done
        z(Starting project development endpoint...)r   r(   r   r5   r   rM   rN   rO   run_commandsrsyncrP   r   )r.   config_itemr3   ssh_connproject_path_uuidproject_path_uuid_devproject_path_uuid_prodremote_project_path	venv_pathcommandsr^   pip_req_pathrK   launch_api_servers                 r4   start_projectr      s#     !""Fi( H HF{FFfY&7&DFFGGGG	"III$VI%6v%>??N  +(**	~	&	& Q1( i !45SSy8I&8QSS 	 !#-> F F!#.?!H!H gll!6)#4V#<
 

 	Y,?YYYY	
 	
 	
 	G,GG/EGGH	
 	
 	

 	6n66777ry{{$9::: GLL!6??	YiYYYY	
 	
 	
 UVI&'78TTTT_i _ _%_ _ 7=Y6GH[6\_ _
 	h''' 	x.CDDDi(0w||	!23F!G
 
 w||	!2>!B
 

[> -?[ [L )M[ [L ,8M[ [x !y[ [H k~I[ [^ Vb_[ [l %m[ [ []
~ 	b			8999/000cQ1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1s   H?KKKc            	         t                      } t          | d         d                   }|st                      }|dS t          |          5 }| d         d          d| d         d          }t          j                            |d          }t          j                            || d         d                   }|                    d| g           t          d	| d
           |	                    t	          j
                    |           t          j                            |d          }t          d| d|            d| d         d          d| d| d| d| d         d          g}|                    |           |                                 ddd           n# 1 swxY w Y   i }| d         d         D ]}	| d         d         |	         ||	<   d| d         d          d}
d| d         d          d| d         d          d| d         d          }d|
z   dz   |z   dz   }t          | d         d          d| d         d          d t          j                     | d         d!         | d         d"         ||d#$          }t          | d         d                   }|sBt!          | d         d          d| d         d          |d%         | d         d&         '          }nt#          |d%         |d%         (          }|d%         S ))zCreate a project endpoint.
    - Move code in dev to prod folder
    - TODO: git commit the diff from current state to new state
    - Create a serverless template for the project
    - Create a new endpoint using the template
    r   r   NrC   ro   rp   r'   rr   rt   z prodru   rv   rq   rw   r%   rJ   z	 -m venv rx   ry   rz   rL   r   z. /runpod-volume/z/prod/venv/bin/activatezpython -u /runpod-volume/z/prod/rK   z	bash -c "z && "z-endpoint | z | r?   rE   T)r'   
image_namecontainer_disk_in_gbdocker_start_cmdenvis_serverlessr&   rB   )r'   template_idnetwork_volume_id)endpoint_idr   )r   r   r5   r   rM   rN   rO   r{   r(   r|   rP   closer
   r   nowr   r	   r   )r.   r3   r~   r   r   r   r   r   r/   r0   activate_cmd
python_cmdr   project_endpoint_templatedeployed_endpoints                  r4   create_project_endpointr   \  s     !""F$VI%6v%>??N  +(**t	~	&	& (i !45SSy8I&8QSS 	 "$.?!H!H gll"F9$5f$=
 

 	@+>@@ABBB;n;;;<<<ry{{$:;;; GLL!7@@	YiYYYY	
 	
 	
 OVI&'78NN9NN_i _ _%_ _ 7=Y6GH[6\_ _
 	h'''7              : 9%j1 R R*0*;J*G*Qh'' 	OF9-f5NNN  NVI->v-F  N  NfU^N_`fNg  N  Njpqzj{  }K  kL  N  NJ"\1F:ZG#M /y!&)eevi7H7PeeU]UaUcUcee)$\2#I./GH)!! ! ! -VI->v-FGG 

+9%f-VV6);LV;TVV1$7$Y/=
 
 
 5)$/1$7
 
 
 T""s   EF!!F%(F%)NNF)'__doc__rM   r+   r   r   r\   r   r   r   r   runpodr   r	   r
   r   r   
runpod.clir   r   r   runpod.cli.utils.ssh_cmdr   utils.rp_syncr   helpersr   r   r   r   r   rN   rO   dirname__file__rS   r5   rm   r   r    r6   r4   <module>r      s    
			 



         0 0 0 0 0 0 0 0 0 0 0 0              > = = = = = = = = = 2 2 2 2 2 2 + + + + + +              GLL!:!:<OPP ( ( (b U/ U/ U/ U/rp1 p1 p1hQ# Q# Q# Q# Q#r6   