Best Testkube code snippet using client.TailJobLogs
job.go
Source:job.go
...137 defer func() {138 c.Log.Debug("closing JobExecutor.Logs out log")139 close(out)140 }()141 if err := c.TailJobLogs(id, logs); err != nil {142 out <- output.NewOutputError(err)143 return144 }145 for l := range logs {146 entry, err := output.GetLogEntry(l)147 if err != nil {148 out <- output.NewOutputError(err)149 return150 }151 out <- entry152 }153 }()154 return155}156// Execute starts new external test execution, reads data and returns ID157// Execution is started asynchronously client can check later for results158func (c JobExecutor) Execute(execution *testkube.Execution, options ExecuteOptions) (result testkube.ExecutionResult, err error) {159 result = testkube.NewRunningExecutionResult()160 ctx := context.Background()161 err = c.CreateJob(ctx, *execution, options)162 if err != nil {163 return result.Err(err), err164 }165 podsClient := c.ClientSet.CoreV1().Pods(c.Namespace)166 pods, err := c.GetJobPods(podsClient, execution.Id, 1, 10)167 if err != nil {168 return result.Err(err), err169 }170 l := c.Log.With("executionID", execution.Id, "type", "async")171 for _, pod := range pods.Items {172 if pod.Status.Phase != corev1.PodRunning && pod.Labels["job-name"] == execution.Id {173 // async wait for complete status or error174 go func(pod corev1.Pod) {175 _, err := c.updateResultsFromPod(ctx, pod, l, execution, result)176 if err != nil {177 l.Errorw("update results from jobs pod error", "error", err)178 }179 }(pod)180 return result, nil181 }182 }183 l.Debugw("no pods was found", "totalPodsCount", len(pods.Items))184 return testkube.NewRunningExecutionResult(), nil185}186// Execute starts new external test execution, reads data and returns ID187// Execution is started synchronously client will be blocked188func (c JobExecutor) ExecuteSync(execution *testkube.Execution, options ExecuteOptions) (result testkube.ExecutionResult, err error) {189 result = testkube.NewRunningExecutionResult()190 ctx := context.Background()191 err = c.CreateJob(ctx, *execution, options)192 if err != nil {193 return result.Err(err), err194 }195 podsClient := c.ClientSet.CoreV1().Pods(c.Namespace)196 pods, err := c.GetJobPods(podsClient, execution.Id, 1, 10)197 if err != nil {198 return result.Err(err), err199 }200 l := c.Log.With("executionID", execution.Id, "type", "sync")201 // get job pod and202 for _, pod := range pods.Items {203 if pod.Status.Phase != corev1.PodRunning && pod.Labels["job-name"] == execution.Id {204 return c.updateResultsFromPod(ctx, pod, l, execution, result)205 }206 }207 l.Debugw("no pods was found", "totalPodsCount", len(pods.Items))208 return209}210// CreateJob creates new Kubernetes job based on execution and execute options211func (c JobExecutor) CreateJob(ctx context.Context, execution testkube.Execution, options ExecuteOptions) error {212 jobs := c.ClientSet.BatchV1().Jobs(c.Namespace)213 jobOptions, err := NewJobOptions(c.initImage, c.jobTemplate, execution, options)214 if err != nil {215 return err216 }217 c.Log.Debug("creating job with options", "options", jobOptions)218 jobSpec, err := NewJobSpec(c.Log, jobOptions)219 if err != nil {220 return err221 }222 _, err = jobs.Create(ctx, jobSpec, metav1.CreateOptions{})223 return err224}225// updateResultsFromPod watches logs and stores results if execution is finished226func (c JobExecutor) updateResultsFromPod(ctx context.Context, pod corev1.Pod, l *zap.SugaredLogger, execution *testkube.Execution, result testkube.ExecutionResult) (testkube.ExecutionResult, error) {227 var err error228 // save stop time and final state229 defer c.stopExecution(ctx, l, execution, &result)230 // wait for complete231 l.Debug("poll immediate waiting for pod to succeed")232 if err = wait.PollImmediate(pollInterval, pollTimeout, IsPodReady(c.ClientSet, pod.Name, c.Namespace)); err != nil {233 // continue on poll err and try to get logs later234 l.Errorw("waiting for pod complete error", "error", err)235 }236 l.Debug("poll immediate end")237 var logs []byte238 logs, err = c.GetPodLogs(pod)239 if err != nil {240 l.Errorw("get pod logs error", "error", err)241 err = c.Repository.UpdateResult(ctx, execution.Id, result.Err(err))242 if err != nil {243 l.Infow("Update result", "error", err)244 }245 return result, err246 }247 // parse job ouput log (JSON stream)248 result, _, err = output.ParseRunnerOutput(logs)249 if err != nil {250 l.Errorw("parse ouput error", "error", err)251 err = c.Repository.UpdateResult(ctx, execution.Id, result.Err(err))252 if err != nil {253 l.Errorw("Update execution result error", "error", err)254 }255 return result, err256 }257 l.Infow("execution completed saving result", "executionId", execution.Id, "status", result.Status)258 err = c.Repository.UpdateResult(ctx, execution.Id, result)259 if err != nil {260 l.Errorw("Update execution result error", "error", err)261 }262 return result, nil263}264func (c JobExecutor) stopExecution(ctx context.Context, l *zap.SugaredLogger, execution *testkube.Execution, result *testkube.ExecutionResult) {265 l.Debug("stopping execution")266 execution.Stop()267 err := c.Repository.EndExecution(ctx, execution.Id, execution.EndTime, execution.CalculateDuration())268 if err != nil {269 l.Errorw("Update execution result error", "error", err)270 }271 // metrics increase272 execution.ExecutionResult = result273 c.metrics.IncExecuteTest(*execution)274 c.Emitter.Notify(testkube.NewEventEndTestSuccess(execution))275}276// NewJobOptionsFromExecutionOptions compose JobOptions based on ExecuteOptions277func NewJobOptionsFromExecutionOptions(options ExecuteOptions) JobOptions {278 return JobOptions{279 Image: options.ExecutorSpec.Image,280 ImageOverride: options.ImageOverride,281 HasSecrets: options.HasSecrets,282 JobTemplate: options.ExecutorSpec.JobTemplate,283 TestName: options.TestName,284 Namespace: options.Namespace,285 SecretEnvs: options.Request.SecretEnvs,286 HTTPProxy: options.Request.HttpProxy,287 HTTPSProxy: options.Request.HttpsProxy,288 UsernameSecret: options.UsernameSecret,289 TokenSecret: options.TokenSecret,290 }291}292// GetJobPods returns job pods293func (c *JobExecutor) GetJobPods(podsClient tcorev1.PodInterface, jobName string, retryNr, retryCount int) (*corev1.PodList, error) {294 pods, err := podsClient.List(context.TODO(), metav1.ListOptions{LabelSelector: "job-name=" + jobName})295 if err != nil {296 return nil, err297 }298 if retryNr == retryCount {299 return nil, fmt.Errorf("retry count exceeeded, there are no active pods with given id=%s", jobName)300 }301 if len(pods.Items) == 0 {302 time.Sleep(time.Duration(retryNr * 500 * int(time.Millisecond))) // increase backoff timeout303 return c.GetJobPods(podsClient, jobName, retryNr+1, retryCount)304 }305 return pods, nil306}307// TailJobLogs - locates logs for job pod(s)308func (c *JobExecutor) TailJobLogs(id string, logs chan []byte) (err error) {309 podsClient := c.ClientSet.CoreV1().Pods(c.Namespace)310 ctx := context.Background()311 pods, err := c.GetJobPods(podsClient, id, 1, 10)312 if err != nil {313 close(logs)314 return err315 }316 for _, pod := range pods.Items {317 if pod.Labels["job-name"] == id {318 l := c.Log.With("podNamespace", pod.Namespace, "podName", pod.Name, "podStatus", pod.Status)319 switch pod.Status.Phase {320 case corev1.PodRunning:321 l.Debug("tailing pod logs: immediately")322 return c.TailPodLogs(ctx, pod, logs)...
run.go
Source:run.go
1package run2import (3 "fmt"4 "io/ioutil"5 "net/url"6 "os"7 "strings"8 "github.com/jenkins-x-labs/helmboot/pkg/clienthelpers"9 "github.com/jenkins-x-labs/helmboot/pkg/cmd/secrets"10 "github.com/jenkins-x-labs/helmboot/pkg/common"11 "github.com/jenkins-x-labs/helmboot/pkg/helmer"12 "github.com/jenkins-x-labs/helmboot/pkg/jxadapt"13 "github.com/jenkins-x-labs/helmboot/pkg/reqhelpers"14 "github.com/jenkins-x-labs/helmboot/pkg/secretmgr"15 "github.com/jenkins-x-labs/helmboot/pkg/secretmgr/factory"16 "github.com/jenkins-x/jx/pkg/cmd/boot"17 "github.com/jenkins-x/jx/pkg/cmd/clients"18 "github.com/jenkins-x/jx/pkg/cmd/helper"19 "github.com/jenkins-x/jx/pkg/cmd/namespace"20 "github.com/jenkins-x/jx/pkg/cmd/opts"21 "github.com/jenkins-x/jx/pkg/cmd/templates"22 "github.com/jenkins-x/jx/pkg/config"23 "github.com/jenkins-x/jx/pkg/gits"24 "github.com/jenkins-x/jx/pkg/kube"25 "github.com/jenkins-x/jx/pkg/log"26 "github.com/jenkins-x/jx/pkg/util"27 "github.com/jenkins-x/jx/pkg/versionstream"28 "github.com/jenkins-x/jx/pkg/versionstream/versionstreamrepo"29 "github.com/pkg/errors"30 "github.com/spf13/cobra"31 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"32)33// RunOptions contains the command line arguments for this command34type RunOptions struct {35 boot.BootOptions36 KindResolver factory.KindResolver37 Gitter gits.Gitter38 ChartName string39 GitUserName string40 GitToken string41 BatchMode bool42 JobMode bool43}44var (45 stepCustomPipelineLong = templates.LongDesc(`46 This command boots up Jenkins and/or Jenkins X in a Kubernetes cluster using GitOps47`)48 stepCustomPipelineExample = templates.Examples(`49 # runs the boot Job to install for the first time50 %s run --git-url https://github.com/myorg/environment-mycluster-dev.git51 # runs the boot Job to upgrade a cluster from the latest in git52 %s run 53`)54)55const (56 defaultChartName = "jx-labs/jxl-boot"57)58// NewCmdRun creates the new command59func NewCmdRun() *cobra.Command {60 options := RunOptions{}61 command := &cobra.Command{62 Use: "run",63 Short: "boots up Jenkins and/or Jenkins X in a Kubernetes cluster using GitOps by triggering a Kubernetes Job inside the cluster",64 Long: stepCustomPipelineLong,65 Example: fmt.Sprintf(stepCustomPipelineExample, common.BinaryName, common.BinaryName),66 Run: func(command *cobra.Command, args []string) {67 common.SetLoggingLevel(command, args)68 err := options.Run()69 helper.CheckErr(err)70 },71 }72 command.Flags().StringVarP(&options.Dir, "dir", "d", ".", "the directory to look for the Jenkins X Pipeline, requirements and charts")73 command.Flags().StringVarP(&options.GitURL, "git-url", "u", "", "override the Git clone URL for the JX Boot source to start from, ignoring the versions stream. Normally specified with git-ref as well")74 command.Flags().StringVarP(&options.GitUserName, "git-user", "", "", "specify the git user name to clone the development git repository. If not specified it is found from the secrets at $JX_SECRETS_YAML")75 command.Flags().StringVarP(&options.GitToken, "git-token", "", "", "specify the git token to clone the development git repository. If not specified it is found from the secrets at $JX_SECRETS_YAML")76 command.Flags().StringVarP(&options.GitRef, "git-ref", "", "master", "override the Git ref for the JX Boot source to start from, ignoring the versions stream. Normally specified with git-url as well")77 command.Flags().StringVarP(&options.ChartName, "chart", "c", defaultChartName, "the chart name to use to install the boot Job")78 command.Flags().StringVarP(&options.VersionStreamURL, "versions-repo", "", common.DefaultVersionsURL, "the bootstrap URL for the versions repo. Once the boot config is cloned, the repo will be then read from the jx-requirements.yml")79 command.Flags().StringVarP(&options.VersionStreamRef, "versions-ref", "", common.DefaultVersionsRef, "the bootstrap ref for the versions repo. Once the boot config is cloned, the repo will be then read from the jx-requirements.yml")80 command.Flags().StringVarP(&options.HelmLogLevel, "helm-log", "v", "", "sets the helm logging level from 0 to 9. Passed into the helm CLI via the '-v' argument. Useful to diagnose helm related issues")81 command.Flags().StringVarP(&options.RequirementsFile, "requirements", "r", "", "requirements file which will overwrite the default requirements file")82 defaultBatchMode := false83 if os.Getenv("JX_BATCH_MODE") == "true" {84 defaultBatchMode = true85 }86 command.PersistentFlags().BoolVarP(&options.BatchMode, "batch-mode", "b", defaultBatchMode, "Runs in batch mode without prompting for user input")87 command.Flags().BoolVarP(&options.JobMode, "job", "", false, "if running inside the cluster lets still default to creating the boot Job rather than running boot locally")88 return command89}90// Run implements the command91func (o *RunOptions) Run() error {92 o.KindResolver.Dir = o.Dir93 if (o.JobMode || !clienthelpers.IsInCluster()) && os.Getenv("JX_DEBUG_JOB") != "true" {94 return o.RunBootJob()95 }96 bo := &o.BootOptions97 if bo.CommonOptions == nil {98 f := clients.NewFactory()99 bo.CommonOptions = opts.NewCommonOptionsWithTerm(f, os.Stdin, os.Stdout, os.Stderr)100 bo.BatchMode = o.BatchMode101 }102 err := o.addUserPasswordForPrivateGitClone(true)103 if err != nil {104 return err105 }106 err = o.verifySecretsYAML()107 if err != nil {108 return err109 }110 return bo.Run()111}112// RunBootJob runs the boot installer Job113func (o *RunOptions) RunBootJob() error {114 err := o.detectGitURL()115 if err != nil {116 return err117 }118 requirements, gitURL, err := reqhelpers.FindRequirementsAndGitURL(o.KindResolver.GetFactory(), o.GitURL, o.Git(), o.Dir)119 if err != nil {120 return err121 }122 if gitURL == "" {123 return util.MissingOption("git-url")124 }125 err = o.addUserPasswordForPrivateGitClone(false)126 if err != nil {127 return errors.Wrapf(err, "could not default the git user and token to clone the git URL")128 }129 clusterName := requirements.Cluster.ClusterName130 log.Logger().Infof("running helmboot Job for cluster %s with git URL %s", util.ColorInfo(clusterName), util.ColorInfo(gitURL))131 log.Logger().Debug("deleting the old jx-boot chart ...")132 c := util.Command{133 Name: "helm",134 Args: []string{"delete", "jx-boot"},135 }136 _, err = c.RunWithoutRetry()137 if err != nil {138 log.Logger().Debugf("failed to delete the old jx-boot chart: %s", err.Error())139 }140 err = o.verifyBootSecret(requirements)141 if err != nil {142 return err143 }144 // lets add helm repository for jx-labs145 h := helmer.NewHelmCLI(o.Dir)146 _, err = helmer.AddHelmRepoIfMissing(h, helmer.LabsChartRepository, "jx-labs", "", "")147 if err != nil {148 return errors.Wrap(err, "failed to add Jenkins X Labs chart repository")149 }150 log.Logger().Infof("updating helm repositories")151 err = h.UpdateRepo()152 if err != nil {153 log.Logger().Warnf("failed to update helm repositories: %s", err.Error())154 }155 version, err := o.findChartVersion(requirements)156 if err != nil {157 return err158 }159 c = reqhelpers.GetBootJobCommand(requirements, gitURL, o.ChartName, version)160 commandLine := fmt.Sprintf("%s %s", c.Name, strings.Join(c.Args, " "))161 log.Logger().Infof("running the command:\n\n%s\n\n", util.ColorInfo(commandLine))162 _, err = c.RunWithoutRetry()163 if err != nil {164 return errors.Wrapf(err, "failed to run command %s", commandLine)165 }166 return o.tailJobLogs()167}168func (o *RunOptions) tailJobLogs() error {169 a := jxadapt.NewJXAdapter(o.KindResolver.GetFactory(), o.Git(), o.BatchMode)170 client, ns, err := o.KindResolver.GetFactory().CreateKubeClient()171 if err != nil {172 return err173 }174 co := a.NewCommonOptions()175 selector := map[string]string{176 "job-name": "jx-boot",177 }178 containerName := "boot"179 podInterface := client.CoreV1().Pods(ns)180 for {181 pod := ""182 if err != nil {183 return err184 }185 pod, err = co.WaitForReadyPodForSelectorLabels(client, ns, selector, false)186 if err != nil {187 return err188 }189 if pod == "" {190 return fmt.Errorf("No pod found for namespace %s with selector %v", ns, selector)191 }192 err = co.TailLogs(ns, pod, containerName)193 if err != nil {194 return nil195 }196 podResource, err := podInterface.Get(pod, metav1.GetOptions{})197 if err != nil {198 return errors.Wrapf(err, "failed to get pod %s in namespace %s", pod, ns)199 }200 if kube.IsPodCompleted(podResource) {201 log.Logger().Infof("the Job pod %s has completed successfully", pod)202 return nil203 }204 log.Logger().Warnf("Job pod %s is not completed but has status: %s", pod, kube.PodStatus(podResource))205 }206}207// Git lazily create a gitter if its not specified208func (o *RunOptions) Git() gits.Gitter {209 if o.Gitter == nil {210 o.Gitter = gits.NewGitCLI()211 }212 return o.Gitter213}214func (o *RunOptions) verifyBootSecret(requirements *config.RequirementsConfig) error {215 if requirements.SecretStorage == config.SecretStorageTypeVault {216 return nil217 }218 _, ns, err := o.KindResolver.GetFactory().CreateKubeClient()219 if err != nil {220 return errors.Wrap(err, "failed to create kube client")221 }222 reqNs := requirements.Cluster.Namespace223 if reqNs != "" && reqNs != ns {224 log.Logger().Infof("switching to the deployment namespace %s as we currently are in the %s namespace", util.ColorInfo(reqNs), util.ColorInfo(ns))225 f := clients.NewFactory()226 no := &namespace.NamespaceOptions{}227 no.CommonOptions = opts.NewCommonOptionsWithTerm(f, os.Stdin, os.Stdout, os.Stderr)228 no.BatchMode = o.BatchMode229 no.Args = []string{reqNs}230 err = no.Run()231 if err != nil {232 return errors.Wrapf(err, "failed to switch to namespace %s", reqNs)233 }234 log.Logger().Infof("switched to the %s namespace", reqNs)235 ns = reqNs236 }237 o.KindResolver.Requirements = requirements238 sm, err := o.KindResolver.CreateSecretManager("")239 if err != nil {240 return errors.Wrap(err, "failed to create Secrets manager")241 }242 secretYaml := ""243 err = sm.UpsertSecrets(func(s string) (string, error) {244 secretYaml = s245 return s, nil246 }, "")247 if err != nil {248 return errors.Wrap(err, "failed to load Secrets YAML")249 }250 if secretYaml == "" {251 return fmt.Errorf("no secrets YAML found. Please run 'jxl boot secrets edit' to populate them")252 }253 err = secretmgr.VerifyBootSecrets(secretYaml)254 if err != nil {255 return errors.Wrapf(err, "invalid secrets yaml looking in namespace %s. Please run 'jxl boot secrets edit' to populate them", ns)256 }257 return nil258}259func (o *RunOptions) findChartVersion(req *config.RequirementsConfig) (string, error) {260 if o.ChartName == "" || o.ChartName[0] == '.' || o.ChartName[0] == '/' || o.ChartName[0] == '\\' || strings.Count(o.ChartName, "/") > 1 {261 // relative chart folder so ignore version262 return "", nil263 }264 f := clients.NewFactory()265 co := opts.NewCommonOptionsWithTerm(f, os.Stdin, os.Stdout, os.Stderr)266 co.BatchMode = o.BatchMode267 u := req.VersionStream.URL268 ref := req.VersionStream.Ref269 version, err := getVersionNumber(versionstream.KindChart, o.ChartName, u, ref, o.Git(), co.GetIOFileHandles())270 if err != nil {271 return version, errors.Wrapf(err, "failed to find version of chart %s in version stream %s ref %s", o.ChartName, u, ref)272 }273 return version, nil274}275// getVersionNumber returns the version number for the given kind and name or blank string if there is no locked version276func getVersionNumber(kind versionstream.VersionKind, name, repo, gitRef string, git gits.Gitter, handles util.IOFileHandles) (string, error) {277 versioner, err := createVersionResolver(repo, gitRef, git, handles)278 if err != nil {279 return "", err280 }281 return versioner.StableVersionNumber(kind, name)282}283// createVersionResolver creates a new VersionResolver service284func createVersionResolver(versionRepository string, versionRef string, git gits.Gitter, handles util.IOFileHandles) (*versionstream.VersionResolver, error) {285 versionsDir, _, err := versionstreamrepo.CloneJXVersionsRepo(versionRepository, versionRef, nil, git, true, false, handles)286 if err != nil {287 return nil, err288 }289 return &versionstream.VersionResolver{290 VersionsDir: versionsDir,291 }, nil292}293func (o *RunOptions) verifySecretsYAML() error {294 yamlFile := os.Getenv("JX_SECRETS_YAML")295 if yamlFile == "" {296 return errors.Errorf("no $JX_SECRETS_YAML defined")297 }298 exists, err := util.FileExists(yamlFile)299 if err != nil {300 return errors.Wrapf(err, "failed to verify secrets YAML file exists: %s", yamlFile)301 }302 eo := &secrets.ExportOptions{303 KindResolver: o.KindResolver,304 OutFile: yamlFile,305 }306 if !exists {307 // lets export the secrets to the yaml file308 err = eo.Run()309 if err != nil {310 return errors.Wrapf(err, "failed to generate the secrets YAML file: %s", yamlFile)311 }312 exists, err = util.FileExists(yamlFile)313 if err != nil {314 return errors.Wrapf(err, "failed to verify secrets YAML file exists after it was generated: %s", yamlFile)315 }316 if !exists {317 return errors.Errorf("no secrets YAML file exists after it was generated: %s", yamlFile)318 }319 }320 err = eo.VerifySecrets()321 if err != nil {322 return errors.Wrapf(err, "failed to verify the secrets for file %s", yamlFile)323 }324 return nil325}326func (o *RunOptions) addUserPasswordForPrivateGitClone(inCluster bool) error {327 err := o.detectGitURL()328 if err != nil {329 return err330 }331 u, err := url.Parse(o.GitURL)332 if err != nil {333 return errors.Wrapf(err, "failed to parse git URL %s", o.GitURL)334 }335 // lets check if we've already got a user and password336 if u.User != nil {337 user := u.User338 pwd, f := user.Password()339 if user.Username() != "" && pwd != "" && f {340 return nil341 }342 }343 username := o.GitUserName344 token := o.GitToken345 if username == "" || token == "" {346 if !inCluster {347 if username == "" {348 return util.MissingOption("git-user")349 }350 return util.MissingOption("git-token")351 }352 yamlFile := os.Getenv("JX_SECRETS_YAML")353 if yamlFile == "" {354 return errors.Errorf("no $JX_SECRETS_YAML defined")355 }356 data, err := ioutil.ReadFile(yamlFile)357 if err != nil {358 return errors.Wrapf(err, "failed to load secrets YAML %s", yamlFile)359 }360 message := fmt.Sprintf("secrets YAML %s", yamlFile)361 username, token, err = secretmgr.PipelineUserTokenFromSecretsYAML(data, message)362 if err != nil {363 return err364 }365 }366 u.User = url.UserPassword(username, token)367 o.GitURL = u.String()368 o.KindResolver.GitURL = o.GitURL369 return nil370}371func (o *RunOptions) detectGitURL() error {372 if o.GitURL == "" {373 // lets try load the git URL from the secret374 gitURL, err := o.KindResolver.LoadBootRunGitURLFromSecret()375 if err != nil {376 return errors.Wrapf(err, "failed to load the boot git URL from the Secret")377 }378 if gitURL == "" {379 log.Logger().Warnf("no git-url specified and no boot git URL Secret found")380 }381 o.GitURL = gitURL382 }383 o.KindResolver.GitURL = o.GitURL384 return nil385}...
TailJobLogs
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")5 if projectID == "" {6 log.Fatal("Missing GOOGLE_CLOUD_PROJECT environment variable")7 }8 bookshelfClient, err := client.NewClient(ctx, projectID)9 if err != nil {10 log.Fatal(err)11 }12 logs, err := bookshelfClient.TailJobLogs(ctx, jobID)13 if err != nil {14 log.Fatal(err)15 }16 for {17 select {18 if !ok {19 fmt.Println("End of logs")20 }21 fmt.Println(log)22 }23 }24}25import (26func main() {27 ctx := context.Background()28 projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")29 if projectID == "" {30 log.Fatal("Missing GOOGLE_CLOUD_PROJECT environment variable")31 }32 bookshelfClient, err := client.NewClient(ctx, projectID)33 if err != nil {34 log.Fatal(err)35 }36 logs, err := bookshelfClient.TailJobLogs(ctx, jobID)37 if err != nil {38 log.Fatal(err)39 }40 for {41 select {42 if !ok {43 fmt.Println("End of logs")44 }45 fmt.Println(log)46 }47 }48}49import (
TailJobLogs
Using AI Code Generation
1import (2func main() {3 svc := batch.New(session.New(), aws.NewConfig().WithRegion("us-east-1"))4 logs, err := svc.GetLogEvents(&batch.GetLogEventsInput{5 LogGroupName: aws.String("/aws/batch/job"),6 LogStreamName: aws.String(logStreamName),7 })8 if err != nil {9 log.Fatal(err)10 }11 for _, e := range logs.Events {12 fmt.Printf("%s", strings.TrimSpace(*e.Message))13 }14 for {15 jobs, err := svc.DescribeJobs(&batch.DescribeJobsInput{16 Jobs: []*string{17 aws.String(jobID),18 },19 })20 if err != nil {21 log.Fatal(err)22 }23 if *jobs.Jobs[0].Status == "FAILED" {24 log.Fatal("Job failed")25 }26 if *jobs.Jobs[0].Status == "SUCCEEDED" {27 }28 time.Sleep(1 * time.Second)29 }30}31import (32func main() {33 svc := batch.New(session.New(), aws.NewConfig().WithRegion("us-east-1"))34 jobs, err := svc.DescribeJobs(&batch.DescribeJobsInput{35 Jobs: []*string{36 aws.String(jobID),37 },38 })39 if err != nil {40 log.Fatal(err)41 }42 fmt.Printf("Status: %s43}
TailJobLogs
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 client, err := client.NewClient(ctx)5 if err != nil {6 log.Fatalf(ctx, "client.NewClient: %v", err)7 }8 defer client.Close()9 it := client.TailJobLogs(ctx, jobName)10 for {11 log, err := it.Next()12 if err == iterator.Done {13 }14 if err != nil {15 log.Fatalf(ctx, "iterator.Next: %v", err)16 }17 fmt.Println(log.Message)18 }19}20import (21func main() {22 ctx := context.Background()23 client, err := client.NewClient(ctx)24 if err != nil {25 log.Fatalf(ctx, "client.NewClient: %v", err)26 }27 defer client.Close()28 it := client.TailJobLogs(ctx, jobName)29 for {30 log, err := it.Next()31 if err == iterator.Done {32 }33 if err != nil {34 log.Fatalf(ctx, "iterator.Next: %v", err)35 }36 fmt.Println(log.Message)37 }38}
TailJobLogs
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 client, err := bookshelf.NewClient(ctx, option.WithServiceAccountFile("C:\\Users\\abc\\Downloads\\key.json"))5 if err != nil {6 log.Fatal(err)7 }8 defer client.Close()9 parent := fmt.Sprintf("projects/%s/locations/%s", "project-id", "us-central1")10 job := &bookshelf.Job{11 CreateTime: time.Now().UTC().Format(time.RFC3339),12 }13 if err := client.CreateJob(ctx, parent, job); err != nil {14 log.Fatal(err)15 }16 job, err = client.GetJob(ctx, job.Name)17 if err != nil {18 log.Fatal(err)19 }20 fmt.Printf("Job: %v21 it := client.ListJobs(ctx, parent)22 for {23 job, err := it.Next()24 if err == iterator.Done {25 }26 if err != nil {27 log.Fatal(err)28 }29 fmt.Printf("Job: %v30 }31 if err := client.UpdateJob(ctx, job); err != nil {32 log.Fatal(err)33 }34 if err := client.DeleteJob(ctx, job.Name); err != nil {35 log.Fatal(err)36 }37 cluster := &bookshelf.Cluster{38 }39 if err := client.CreateCluster(ctx, cluster); err != nil {40 log.Fatal(err)41 }42 cluster, err = client.GetCluster(ctx, cluster.Name)
TailJobLogs
Using AI Code Generation
1import (2func main() {3 client, err := bookshelf.NewClient("projectID")4 if err != nil {5 log.Fatal(err)6 }7 logs := client.TailJobLogs(jobID)8 for log := range logs {9 fmt.Println(log)10 }11}
TailJobLogs
Using AI Code Generation
1import (2func main() {3 client, err := bookshelf.NewClient()4 if err != nil {5 log.Fatal(err)6 }7 if err := client.TailJobLogs(jobID, timeout); err != nil {
TailJobLogs
Using AI Code Generation
1import (2func main() {3 client, err := bookshelf.NewClient()4 if err != nil {5 fmt.Println(err)6 }7 err = client.TailJobLogs("my-job")8 if err != nil {9 fmt.Println(err)10 }11}12import (13func main() {14 client, err := bookshelf.NewClient()15 if err != nil {16 fmt.Println(err)17 }18 jobs, err := client.ListJobs()19 if err != nil {20 fmt.Println(err)21 }22 fmt.Println(jobs)23}24import (25func main() {26 client, err := bookshelf.NewClient()27 if err != nil {28 fmt.Println(err)29 }30 job, err := client.GetJob("my-job")31 if err != nil {32 fmt.Println(err)33 }34 fmt.Println(job)35}36import (37func main() {38 client, err := bookshelf.NewClient()39 if err != nil {40 fmt.Println(err)41 }42 status, err := client.GetJobStatus("my-job")43 if err != nil {44 fmt.Println(err)45 }46 fmt.Println(status)47}48import (49func main() {
TailJobLogs
Using AI Code Generation
1import (2func main() {3 client, err := jobs.NewService(testutil.Context(nil))4 if err != nil {5 fmt.Println(err)6 }7 req := &jobs.TailJobLogsRequest{
TailJobLogs
Using AI Code Generation
1import (2func main() {3 oc, err := client.New(&client.Config{4 })5 if err != nil {6 log.Fatalf("Error in creating the client: %v", err)7 }8 ns := os.Getenv("OPENSHIFT_BUILD_NAMESPACE")9 if len(ns) == 0 {10 log.Fatalf("Error in getting the namespace")11 }12 name := os.Getenv("OPENSHIFT_BUILD_NAME")13 if len(name) == 0 {14 log.Fatalf("Error in getting the build name")15 }16 logs, err := oc.BuildLogs(ns).Get(name, &buildapi.BuildLogOptions{Follow: true})17 if err != nil {18 log.Fatalf("Error in getting the build logs: %v", err)19 }20 defer logs.Close()21 buf := make([]byte, 1024)22 for {23 n, err := logs.Read(buf)24 if err != nil {25 if err != io.EOF {26 log.Fatalf("Error in reading the build logs: %v", err)27 }28 }29 if n > 0 {30 fmt.Printf("%s", string(buf[:n]))31 }32 }33}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!