2017-11-18 12:51:28 +00:00
|
|
|
package k8s
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
"k8s.io/api/batch/v1"
|
|
|
|
corev1 "k8s.io/api/core/v1"
|
2017-12-20 23:11:50 +00:00
|
|
|
"k8s.io/client-go/kubernetes"
|
2017-11-18 12:51:28 +00:00
|
|
|
|
|
|
|
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
|
|
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
|
|
|
)
|
|
|
|
|
2018-05-07 21:51:09 +00:00
|
|
|
func ApplyK8sSystemJob(jobYaml, kubeConfigPath string, k8sWrapTransport WrapTransport, timeout int) error {
|
2017-11-18 12:51:28 +00:00
|
|
|
job := v1.Job{}
|
2017-12-20 23:11:50 +00:00
|
|
|
if err := decodeYamlResource(&job, jobYaml); err != nil {
|
2017-11-18 12:51:28 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
if job.Namespace == metav1.NamespaceNone {
|
|
|
|
job.Namespace = metav1.NamespaceSystem
|
|
|
|
}
|
2018-02-20 11:51:57 +00:00
|
|
|
k8sClient, err := NewClient(kubeConfigPath, k8sWrapTransport)
|
2017-11-18 12:51:28 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if _, err = k8sClient.BatchV1().Jobs(job.Namespace).Create(&job); err != nil {
|
|
|
|
if apierrors.IsAlreadyExists(err) {
|
|
|
|
logrus.Debugf("[k8s] Job %s already exists..", job.Name)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
2017-11-23 00:12:30 +00:00
|
|
|
logrus.Debugf("[k8s] waiting for job %s to complete..", job.Name)
|
2018-05-07 21:51:09 +00:00
|
|
|
return retryToWithTimeout(ensureJobCompleted, k8sClient, job, timeout)
|
2017-12-20 23:11:50 +00:00
|
|
|
}
|
2017-11-18 12:51:28 +00:00
|
|
|
|
2017-12-20 23:11:50 +00:00
|
|
|
func ensureJobCompleted(k8sClient *kubernetes.Clientset, j interface{}) error {
|
|
|
|
job := j.(v1.Job)
|
|
|
|
existingJob := &v1.Job{}
|
|
|
|
existingJob, err := k8sClient.BatchV1().Jobs(job.Namespace).Get(job.Name, metav1.GetOptions{})
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Failed to update job status: %v", err)
|
2017-11-18 12:51:28 +00:00
|
|
|
|
|
|
|
}
|
2017-12-20 23:11:50 +00:00
|
|
|
for _, condition := range existingJob.Status.Conditions {
|
|
|
|
if condition.Type == v1.JobComplete && condition.Status == corev1.ConditionTrue {
|
|
|
|
logrus.Debugf("[k8s] Job %s completed successfully..", job.Name)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
2017-11-18 12:51:28 +00:00
|
|
|
return fmt.Errorf("Failed to get job complete status: %v", err)
|
|
|
|
}
|