Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use nslookup in the init container #92

Merged
merged 2 commits into from
Apr 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 20 additions & 79 deletions controllers/paddlejob_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ package controllers
import (
"context"
"fmt"
"net/http"
"os"
"reflect"
"time"

Expand All @@ -30,9 +28,6 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"

"k8s.io/client-go/rest"
"k8s.io/client-go/tools/remotecommand"

corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
Expand All @@ -57,10 +52,8 @@ var (
// PaddleJobReconciler reconciles a PaddleJob object
type PaddleJobReconciler struct {
client.Client
Scheme *runtime.Scheme
Recorder record.EventRecorder
RESTClient rest.Interface
RESTConfig *rest.Config
Scheme *runtime.Scheme
Recorder record.EventRecorder

Scheduling string
InitImage string
Expand Down Expand Up @@ -161,25 +154,25 @@ func (r *PaddleJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (
// List all associated svc
var svcs corev1.ServiceList

if pdj.Spec.Intranet == pdv1.Service {
if err := r.List(ctx, &svcs, client.InNamespace(req.Namespace), client.MatchingFields{ctrlRefKey: req.Name}); err != nil {
return ctrl.Result{}, err
}
//if pdj.Spec.Intranet == pdv1.Service {
if err := r.List(ctx, &svcs, client.InNamespace(req.Namespace), client.MatchingFields{ctrlRefKey: req.Name}); err != nil {
return ctrl.Result{}, err
}

// Ensure service for running pod
for _, pod := range childPods.Items {
svc := constructService4Pod(pod)
if err := r.Get(ctx, client.ObjectKeyFromObject(svc), &corev1.Service{}); err == nil {
continue
}
if err := ctrl.SetControllerReference(&pdj, svc, r.Scheme); err != nil {
logr.Error(err, "make reference failed")
continue
}
err := r.createResource(ctx, &pdj, svc)
return ctrl.Result{}, err
// Ensure service for running pod
for _, pod := range childPods.Items {
svc := constructService4Pod(pod)
if err := r.Get(ctx, client.ObjectKeyFromObject(svc), &corev1.Service{}); err == nil {
continue
}
if err := ctrl.SetControllerReference(&pdj, svc, r.Scheme); err != nil {
logr.Error(err, "make reference failed")
continue
}
err := r.createResource(ctx, &pdj, svc)
return ctrl.Result{}, err
}
//}

cleanOne := func() {
for i := range childPods.Items {
Expand Down Expand Up @@ -213,7 +206,8 @@ func (r *PaddleJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (
pod := constructPod(&pdj, resType, idx)

if r.InitImage != "" {
coInit := genCoordinateInitContainer(r.InitImage)
initCmd := genCoordContainerCmd(&pdj, resType)
coInit := genCoordinateInitContainer(r.InitImage, initCmd)
pod.Spec.InitContainers = append(pod.Spec.InitContainers, coInit)
}

Expand Down Expand Up @@ -271,30 +265,6 @@ func (r *PaddleJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (
}
}

runResource := func(resType string) {
for i, pod := range childPods.Items {
if resType == pod.Annotations[pdv1.ResourceAnnotation] {
if isCoordContainerRunning(&childPods.Items[i]) {
r.execInPod(pdj.Namespace, pod.Name, coordContainerName, []string{"touch", "goon"})
}
}
}
}

// coordinate ensure pod run in the defined order
if pdj.Status.Phase == pdv1.Starting && r.InitImage != "" {
ress := pdj.GetResourceOrder()
for i := 0; i < len(ress); i++ {
if statuses[ress[i]] != nil && statuses[ress[i]].Running < specs[ress[i]].Replicas {
if i == 0 && statuses[ress[i]].Running == 0 && !isAllCoordContainerRunning(childPods) {
return ctrl.Result{RequeueAfter: time.Second}, nil
}
runResource(ress[i])
return ctrl.Result{RequeueAfter: time.Second}, nil
}
}
}

return ctrl.Result{}, nil
}

Expand Down Expand Up @@ -391,35 +361,6 @@ func (r *PaddleJobReconciler) finalize(ctx context.Context, pdj *pdv1.PaddleJob)
return false
}

func (r *PaddleJobReconciler) execInPod(namespace string, podName string, containerName string, cmd []string) error {
execReq := r.RESTClient.
Post().
Namespace(namespace).
Resource("pods").
Name(podName).
SubResource("exec").
VersionedParams(&corev1.PodExecOptions{
Container: containerName,
Command: cmd,
Stdout: true,
Stderr: true,
}, runtime.NewParameterCodec(r.Scheme)).Timeout(3 * time.Second)

exec, err := remotecommand.NewSPDYExecutor(r.RESTConfig, http.MethodPost, execReq.URL())
if err != nil {
return err
}

err = exec.Stream(remotecommand.StreamOptions{
Stdin: nil,
Stdout: os.Stdout,
Stderr: os.Stderr,
Tty: false,
})

return err
}

func indexerFunc(rawObj client.Object) []string {
owner := metav1.GetControllerOf(rawObj)
if owner == nil {
Expand Down
22 changes: 16 additions & 6 deletions controllers/paddlejob_helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,7 @@ const (
coordContainerName = "coord-paddle"
coordContainerCpu = "10m"
coordContainerMem = "10m"
)

var (
coordContainerCmd = []string{"sh", "-c", "while true; do if [ -f goon ]; then exit 0; else sleep 0.1; fi; done"}
coordContainerSh = "for h in %s; do for i in $(seq 1000); do echo check $i; if nslookup $h; then break; fi; if [ $i -eq 1000 ]; then exit 1; fi; sleep 1; done; done; sleep 2"
)

func isAllPodsReady(pdj *pdv1.PaddleJob, childPods corev1.PodList) bool {
Expand Down Expand Up @@ -376,7 +373,7 @@ func constructPod(pdj *pdv1.PaddleJob, resType string, idx int) (pod *corev1.Pod
return pod
}

func genCoordinateInitContainer(coordContainerImage string) corev1.Container {
func genCoordinateInitContainer(coordContainerImage string, coordContainerCmd []string) corev1.Container {
c := corev1.Container{
Name: coordContainerName,
Image: coordContainerImage,
Expand All @@ -393,6 +390,18 @@ func genCoordinateInitContainer(coordContainerImage string) corev1.Container {
return c
}

func genCoordContainerCmd(pdj *pdv1.PaddleJob, resType string) []string {
specs := pdj.GetSpecs()
names := []string{}
for idx := 0; idx < specs[resType].Replicas; idx++ {
names = append(names, fmt.Sprintf("\"%s-%s-%d\"", pdj.Name, resType, idx))
}
hosts := strings.Join(names, " ")
sc := fmt.Sprintf(coordContainerSh, hosts)
ret := []string{"sh", "-c", sc}
return ret
}

func endpoints2hosts(eps []string) string {
hosts := make([]string, len(eps))
for i, ep := range eps {
Expand Down Expand Up @@ -448,7 +457,8 @@ func constructService4Pod(pod corev1.Pod) *corev1.Service {
Selector: map[string]string{
pdv1.ResourceName: pod.Name,
},
ClusterIP: "None",
PublishNotReadyAddresses: true,
ClusterIP: "None",
},
}
return svc
Expand Down
19 changes: 1 addition & 18 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,6 @@ import (
"sigs.k8s.io/controller-runtime/pkg/healthz"
"sigs.k8s.io/controller-runtime/pkg/log/zap"

"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"

volcano "volcano.sh/apis/pkg/apis/scheduling/v1beta1"

batchv1 "github.com/paddleflow/paddle-operator/api/v1"
Expand Down Expand Up @@ -69,7 +65,7 @@ func main() {
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")
flag.StringVar(&scheduling, "scheduling", "", "The scheduler to take, e.g. volcano")
flag.StringVar(&initImage, "initImage", "docker.io/library/busybox:1", "The image used for init container, default to busybox")
flag.StringVar(&initImage, "initImage", "docker.io/library/alpine:3.10", "The image used for init container, default to alpine")
opts := zap.Options{
Development: true,
}
Expand All @@ -92,23 +88,10 @@ func main() {
os.Exit(1)
}

// restClient for exec
gvk := schema.GroupVersionKind{
Group: "",
Version: "v1",
Kind: "Pod",
}
restClient, err := apiutil.RESTClientForGVK(gvk, false, mgr.GetConfig(), serializer.NewCodecFactory(mgr.GetScheme()))
if err != nil {
setupLog.Error(err, "unable to create REST client")
}

if err = (&controllers.PaddleJobReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
Recorder: mgr.GetEventRecorderFor("paddlejob-controller"),
RESTClient: restClient,
RESTConfig: mgr.GetConfig(),
Scheduling: scheduling,
InitImage: initImage,
}).SetupWithManager(mgr); err != nil {
Expand Down