github.com/munnerz/test-infra@v0.0.0-20190108210205-ce3d181dc989/experiment/tracer/main.go (about)

     1  /*
     2  Copyright 2018 The Kubernetes 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 main
    18  
    19  import (
    20  	"flag"
    21  	"fmt"
    22  	"net/http"
    23  	"time"
    24  
    25  	"github.com/NYTimes/gziphandler"
    26  	"github.com/sirupsen/logrus"
    27  	"k8s.io/apimachinery/pkg/labels"
    28  
    29  	"k8s.io/test-infra/prow/kube"
    30  )
    31  
    32  var (
    33  	selector  = flag.String("label-selector", "", "Label selector to select prow pods for log tracing. See https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors for constructing a label selector.")
    34  	namespace = flag.String("namespace", "", "Namespace where prow runs")
    35  	headless  = flag.Bool("headless", false, "Run on headless mode")
    36  )
    37  
    38  func main() {
    39  	flag.Parse()
    40  	logrus.SetFormatter(&logrus.JSONFormatter{})
    41  	logger := logrus.WithField("component", "tracer")
    42  
    43  	if err := validateOptions(); err != nil {
    44  		logrus.Fatal(err)
    45  	}
    46  
    47  	kc, err := kube.NewClientInCluster(*namespace)
    48  	if err != nil {
    49  		logger.WithError(err).Fatal("Error getting k8s client.")
    50  	}
    51  
    52  	mux := http.NewServeMux()
    53  	if !*headless {
    54  		mux.Handle("/", gziphandler.GzipHandler(http.FileServer(http.Dir("/static"))))
    55  	}
    56  	mux.Handle("/trace", gziphandler.GzipHandler(handleTrace(*selector, kc)))
    57  
    58  	server := &http.Server{
    59  		Addr:         ":8080",
    60  		Handler:      mux,
    61  		ReadTimeout:  2 * time.Minute,
    62  		WriteTimeout: 2 * time.Minute,
    63  	}
    64  	logrus.Fatal(server.ListenAndServe())
    65  }
    66  
    67  func validateOptions() error {
    68  	if *selector == "" {
    69  		return fmt.Errorf("you need to specify a label selector")
    70  	}
    71  	if _, err := labels.Parse(*selector); err != nil {
    72  		return err
    73  	}
    74  	if *namespace == "" {
    75  		return fmt.Errorf("you need to specify a namespace")
    76  	}
    77  	return nil
    78  }