github.com/GoogleCloudPlatform/testgrid@v0.0.174/pkg/summarizer/pubsub.go (about)

     1  /*
     2  Copyright 2021 The TestGrid Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package summarizer
    18  
    19  import (
    20  	"context"
    21  	"errors"
    22  	"math/rand"
    23  	"net/url"
    24  	"path"
    25  	"strings"
    26  	"sync"
    27  	"time"
    28  
    29  	"github.com/GoogleCloudPlatform/testgrid/config"
    30  	"github.com/GoogleCloudPlatform/testgrid/pkg/pubsub"
    31  	"github.com/GoogleCloudPlatform/testgrid/util/gcs"
    32  	"github.com/sirupsen/logrus"
    33  )
    34  
    35  // FixGCS listens for GCS changes to test groups and schedules another update of its dashboards ~immediately.
    36  //
    37  // Returns when the context is canceled or a processing error occurs.
    38  func FixGCS(client pubsub.Subscriber, log logrus.FieldLogger, projID, subID string, configPath gcs.Path, tabPathPrefix string) (Fixer, error) {
    39  	if !strings.HasSuffix(tabPathPrefix, "/") && tabPathPrefix != "" {
    40  		tabPathPrefix += "/"
    41  	}
    42  	gridPath, err := configPath.ResolveReference(&url.URL{Path: tabPathPrefix})
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  	return func(ctx context.Context, q *config.DashboardQueue) error {
    47  		ctx, cancel := context.WithCancel(ctx)
    48  		defer cancel()
    49  		ch := make(chan *pubsub.Notification)
    50  		var wg sync.WaitGroup
    51  		wg.Add(1)
    52  		go func() {
    53  			defer wg.Done()
    54  			for {
    55  				err := pubsub.SendGCS(ctx, log, client, projID, subID, nil, ch)
    56  				if err == nil {
    57  					return
    58  				}
    59  				if errors.Is(err, context.Canceled) || ctx.Err() != nil {
    60  					log.WithError(err).Trace("Subscription canceled")
    61  					return
    62  				}
    63  				sleep := time.Minute + time.Duration(rand.Int63n(int64(time.Minute)))
    64  				log.WithError(err).WithField("sleep", sleep).Error("Error receiving GCS notifications, will retry...")
    65  				time.Sleep(sleep)
    66  			}
    67  		}()
    68  		defer wg.Wait()
    69  		return processGCSNotifications(ctx, log, q, *gridPath, tabPathPrefix != "", ch)
    70  	}, nil
    71  }
    72  
    73  func processGCSNotifications(ctx context.Context, log logrus.FieldLogger, q *config.DashboardQueue, gridPrefix gcs.Path, findDashboard bool, senders <-chan *pubsub.Notification) error {
    74  	for {
    75  		select {
    76  		case <-ctx.Done():
    77  			return ctx.Err()
    78  		case notice, ok := <-senders:
    79  			if !ok {
    80  				return nil
    81  			}
    82  			group := processNotification(gridPrefix, findDashboard, notice)
    83  			if group == nil {
    84  				continue
    85  			}
    86  			const delay = 5 * time.Second
    87  			when := notice.Time.Add(delay)
    88  			log.WithFields(logrus.Fields{
    89  				"group":        group,
    90  				"when":         when,
    91  				"notification": notice,
    92  			}).Trace("Fixing groups from gcs notifcation")
    93  			if err := q.FixTestGroups(when, false, *group); err != nil {
    94  				return err
    95  			}
    96  		}
    97  	}
    98  }
    99  
   100  // Return the test group/dashboard associated with the notification.
   101  func processNotification(gridPrefix gcs.Path, wantDashboard bool, n *pubsub.Notification) *string {
   102  	if gridPrefix.Bucket() != n.Path.Bucket() {
   103  		return nil
   104  	}
   105  
   106  	dir, base := path.Split(n.Path.Object()) // gs://prefix/TEST_GROUP
   107  	if wantDashboard && len(dir) > 0 {       // Actually, gs://prefix/DASH/TAB
   108  		dir, base = path.Split(dir[:len(dir)-1])
   109  	}
   110  	if dir != gridPrefix.Object() {
   111  		return nil
   112  	}
   113  	return &base // gs://prefix/TEST_GROUP
   114  }