Elffuss BraidHub

kikocis/continue public

main · 2.2 KiB · executableRawPermalink
1#!/bin/bash
2
3# Timeout for waiting for Ollama to start (in seconds)
4readonly TIMEOUT=60
5readonly OLLAMA_API_URL="http://localhost:11434/api/version"
6
7# Check if a command exists
8command_exists() {
9 command -v "$1" >/dev/null 2>&1
10}
11
12# Check if Ollama is already running
13ollama_is_running() {
14 VERSION=$(curl -s --fail --max-time 1 "$OLLAMA_API_URL" | grep '"version"' | awk -F: '{ print $2 }' | sed -e 's/.*"\([^"]*\)".*/\1/')
15 test -n "$VERSION"
16}
17
18# Determine if running in a container environment
19in_container() {
20 [[ -f /.dockerenv || -f /run/.containerenv ]]
21}
22
23# Start Ollama service or background process
24start_ollama() {
25 local start_method="${1:-background}"
26 echo "Starting Ollama ($start_method)..."
27
28 if [[ "$start_method" == "service" ]]; then
29 if in_container; then
30 service ollama start || return $?
31 else
32 sudo systemctl start ollama || return $?
33 fi
34 else
35 nohup ollama serve >/dev/null 2>&1 &
36 fi
37
38 # Wait for Ollama to start. TIMEOUT * 4, since we sleep 1/4 sec on each iteration
39 for _ in $(seq 1 $((TIMEOUT * 4))); do
40 if ollama_is_running; then
41 echo -e "\nOllama started successfully."
42 return 0
43 fi
44 (( _ % 2 == 0 )) && printf "."
45 sleep 0.25
46 done
47
48 echo -e "\nTimeout: Failed to start Ollama."
49 return 1
50}
51
52# Main script execution
53main() {
54 # Early exit if Ollama is already running
55 if ollama_is_running; then
56 echo "Ollama is already running."
57 return 0
58 fi
59
60 # Try starting via service if possible
61 if in_container; then
62 if service --status-all 2>&1 | grep -qw 'ollama'; then
63 start_ollama service || return $?
64 return 0
65 fi
66 elif command_exists systemctl; then
67 if systemctl list-unit-files ollama.service >/dev/null 2>&1; then
68 start_ollama service || return $?
69 return 0
70 fi
71 fi
72
73 # Fallback to background process
74 if command_exists ollama; then
75 start_ollama || return 1
76 else
77 echo "Error: Ollama is not installed or not in the PATH." >&2
78 return 1
79 fi
80}
81
82# Run the main function and exit with its status
83main
84exit $?