github.com/galamsiva2020/kubernetes-heapster-monitoring@v0.0.0-20210823134957-3c1baa7c1e70/grafana/setup_grafana.go (about)

     1  // Copyright 2014 Google Inc. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package main
    16  
    17  import (
    18  	"bytes"
    19  	"encoding/json"
    20  	"fmt"
    21  	"io/ioutil"
    22  	"net/http"
    23  	"os"
    24  	"path/filepath"
    25  	"strings"
    26  	"time"
    27  )
    28  
    29  // How many seconds the program should wait before trying to connect to the dashboard again
    30  const RetryTimeout = 5
    31  
    32  type grafanaConfig struct {
    33  	Name      string `json:"name"`
    34  	Type      string `json:"type"`
    35  	Access    string `json:"access"`
    36  	IsDefault bool   `json:"isDefault"`
    37  	URL       string `json:"url"`
    38  	Password  string `json:"password"`
    39  	User      string `json:"user"`
    40  	Database  string `json:"database"`
    41  }
    42  
    43  func main() {
    44  
    45  	envParams := map[string]string{
    46  		"grafana_user":               "admin",
    47  		"grafana_passwd":             "admin",
    48  		"grafana_port":               "3000",
    49  		"influxdb_host":              "monitoring-influxdb",
    50  		"influxdb_port":              "8086",
    51  		"influxdb_database":          "k8s",
    52  		"influxdb_user":              "root",
    53  		"influxdb_password":          "root",
    54  		"influxdb_service_url":       "",
    55  		"dashboard_location":         "/dashboards",
    56  		"gf_auth_anonymous_enabled":  "true",
    57  		"gf_security_admin_user":     "",
    58  		"gf_security_admin_password": "",
    59  		"gf_server_http_port":        "",
    60  		"gf_server_protocol":         "http",
    61  		"backend_access_mode":        "proxy",
    62  	}
    63  
    64  	for k := range envParams {
    65  		if v := os.Getenv(strings.ToUpper(k)); v != "" {
    66  			envParams[k] = v
    67  		}
    68  	}
    69  
    70  	if envParams["influxdb_service_url"] == "" {
    71  		envParams["influxdb_service_url"] = fmt.Sprintf("http://%s:%s", envParams["influxdb_host"], envParams["influxdb_port"])
    72  	}
    73  
    74  	cfg := grafanaConfig{
    75  		Name:      "influxdb-datasource",
    76  		Type:      "influxdb",
    77  		Access:    envParams["backend_access_mode"],
    78  		IsDefault: true,
    79  		URL:       envParams["influxdb_service_url"],
    80  		User:      envParams["influxdb_user"],
    81  		Password:  envParams["influxdb_password"],
    82  		Database:  envParams["influxdb_database"],
    83  	}
    84  	// Override setup env vars with Grafana configuration env vars if present
    85  	adminUser := envParams["grafana_user"]
    86  	if user, ok := envParams["gf_security_admin_user"]; ok && len(user) != 0 {
    87  		adminUser = user
    88  	}
    89  	adminPassword := envParams["grafana_passwd"]
    90  	if password, ok := envParams["gf_security_admin_password"]; ok && len(password) != 0 {
    91  		adminPassword = password
    92  	}
    93  	httpPort := envParams["grafana_port"]
    94  	if port, ok := envParams["gf_server_http_port"]; ok && len(port) != 0 {
    95  		httpPort = port
    96  	}
    97  
    98  	grafanaURL := fmt.Sprintf("%s://%s:%s@localhost:%s", envParams["gf_server_protocol"], adminUser, adminPassword, httpPort)
    99  
   100  	for {
   101  		res, err := http.Get(grafanaURL + "/api/org")
   102  		if err != nil {
   103  			fmt.Printf("Can't access the Grafana dashboard. Error: %v. Retrying after %d seconds...\n", err, RetryTimeout)
   104  			time.Sleep(RetryTimeout * time.Second)
   105  			continue
   106  		}
   107  
   108  		_, err = ioutil.ReadAll(res.Body)
   109  		res.Body.Close()
   110  		if err != nil {
   111  			fmt.Printf("Can't access the Grafana dashboard. Error: %v. Retrying after %d seconds...\n", err, RetryTimeout)
   112  			time.Sleep(RetryTimeout * time.Second)
   113  			continue
   114  		}
   115  
   116  		fmt.Println("Connected to the Grafana dashboard.")
   117  		break
   118  	}
   119  
   120  	b := new(bytes.Buffer)
   121  	json.NewEncoder(b).Encode(cfg)
   122  
   123  	for {
   124  		_, err := http.Post(grafanaURL+"/api/datasources", "application/json; charset=utf-8", b)
   125  		if err != nil {
   126  			fmt.Printf("Failed to configure the Grafana dashboard. Error: %v. Retrying after %d seconds...\n", err, RetryTimeout)
   127  			time.Sleep(RetryTimeout * time.Second)
   128  			continue
   129  		}
   130  
   131  		fmt.Println("The datasource for the Grafana dashboard is now set.")
   132  		break
   133  	}
   134  
   135  	dashboardDir := envParams["dashboard_location"]
   136  	files, err := ioutil.ReadDir(dashboardDir)
   137  	if err != nil {
   138  		fmt.Printf("Failed to read the directory the json files should be in. Exiting... Error: %v\n", err)
   139  		os.Exit(1)
   140  	}
   141  	for _, file := range files {
   142  		if file.IsDir() {
   143  			continue
   144  		}
   145  
   146  		filePath := filepath.Join(dashboardDir, file.Name())
   147  		jsonbytes, err := ioutil.ReadFile(filePath)
   148  		if err != nil {
   149  			fmt.Printf("Failed to read the json file: %s. Proceeding with the next one. Error: %v\n", filePath, err)
   150  			continue
   151  		}
   152  
   153  		_, err = http.Post(grafanaURL+"/api/dashboards/db", "application/json; charset=utf-8", bytes.NewReader(jsonbytes))
   154  		if err != nil {
   155  			fmt.Printf("Failed to post the json file: %s. Proceeding with the next one. Error: %v\n", filePath, err)
   156  			continue
   157  		}
   158  	}
   159  }