main.go
1 // Copyright 2025 Alibaba Group Holding Ltd. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package main 16 17 import ( 18 "context" 19 "fmt" 20 "log" 21 "time" 22 23 taskexecutor "github.com/alibaba/OpenSandbox/sandbox-k8s/pkg/task-executor" 24 ) 25 26 func main() { 27 baseURL := "http://localhost:5758" 28 client := taskexecutor.NewClient(baseURL) 29 ctx := context.Background() 30 31 fmt.Printf("Connecting to Task Executor at %s...\n", baseURL) 32 33 taskName := "example-task" 34 newTask := &taskexecutor.Task{ 35 Name: taskName, 36 Process: &taskexecutor.Process{ 37 Command: []string{"sh", "-c"}, 38 Args: []string{"echo 'Hello from SDK example!' && sleep 2 && echo 'Task done.'"}, 39 }, 40 } 41 42 fmt.Printf("Submitting task '%s'...\n", taskName) 43 createdTask, err := client.Set(ctx, newTask) 44 if err != nil { 45 log.Fatalf("Failed to set task: %v", err) 46 } 47 fmt.Printf("Task submitted successfully. Initial state: %v\n", getTaskState(createdTask)) 48 49 fmt.Println("Polling task status...") 50 for i := 0; i < 10; i++ { 51 currentTask, err := client.Get(ctx) 52 if err != nil { 53 log.Printf("Error getting task: %v", err) 54 continue 55 } 56 57 if currentTask == nil { 58 fmt.Println("No task found.") 59 break 60 } 61 62 state := getTaskState(currentTask) 63 fmt.Printf("Current state: %s\n", state) 64 65 // Check if task is finished 66 if currentTask.ProcessStatus.Terminated != nil { 67 fmt.Printf("Task finished with exit code: %d\n", currentTask.ProcessStatus.Terminated.ExitCode) 68 break 69 } 70 71 time.Sleep(500 * time.Millisecond) 72 } 73 74 // Clean up (pass nil to clear tasks) 75 fmt.Println("Cleaning up...") 76 _, err = client.Set(ctx, nil) 77 if err != nil { 78 log.Printf("Failed to clear tasks: %v", err) 79 } else { 80 fmt.Println("Tasks cleared.") 81 } 82 } 83 84 // getTaskState returns a string representation of the task state 85 func getTaskState(task *taskexecutor.Task) string { 86 if task == nil { 87 return "Unknown" 88 } 89 if task.ProcessStatus.Running != nil { 90 return "Running" 91 } 92 if task.ProcessStatus.Terminated != nil { 93 return "Terminated" 94 } 95 if task.ProcessStatus.Waiting != nil { 96 return fmt.Sprintf("Waiting (%s)", task.ProcessStatus.Waiting.Reason) 97 } 98 return "Pending" 99 }