|
| 1 | +package util |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "io/ioutil" |
| 8 | + "log" |
| 9 | + "net/http" |
| 10 | + "os" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/olivere/elastic/v7" |
| 14 | +) |
| 15 | + |
| 16 | +var TimeValidity int64 |
| 17 | +var MAX_ALLOWED_TIME int64 = 24 // in hrs |
| 18 | + |
| 19 | +type ArcUsage struct { |
| 20 | + ArcID string `json:"arc_id"` |
| 21 | + Timestamp int64 `json:"timestamp"` |
| 22 | + SubscriptionID string `json:"subscription_id"` |
| 23 | + Quantity int `json:"quantity"` |
| 24 | + Email string `json:"email"` |
| 25 | +} |
| 26 | + |
| 27 | +type ArcUsageResponse struct { |
| 28 | + Accepted bool `json:"accepted"` |
| 29 | + FailureReason string `json:"failure_reason"` |
| 30 | + ErrorMsg string `json:"error_msg"` |
| 31 | + WarningMsg string `json:"warning_msg"` |
| 32 | + StatusCode int `json:"status_code"` |
| 33 | + TimeValidity int64 `json:"time_validity"` |
| 34 | +} |
| 35 | + |
| 36 | +const ( |
| 37 | + envEsURL = "ES_CLUSTER_URL" |
| 38 | + arcIdentifier = "ARC_ID" |
| 39 | + emailID = "EMAIL" |
| 40 | + subscriptionID = "SUBSCRIPTION_ID" |
| 41 | +) |
| 42 | + |
| 43 | +// Middleware function, which will be called for each request |
| 44 | +func BillingMiddleware(next http.Handler) http.Handler { |
| 45 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 46 | + if TimeValidity > 0 { // Valid plan |
| 47 | + next.ServeHTTP(w, r) |
| 48 | + } else if -(TimeValidity) <= 3600*MAX_ALLOWED_TIME { |
| 49 | + // Print warning message if remaining time is less than max allowed time |
| 50 | + if TimeValidity == 0 { // Rare, but it can happen when tier has been just expired |
| 51 | + log.Println("warning: payment required. arc will start sending out error messages in some time") |
| 52 | + } else { |
| 53 | + log.Println("warning: payment required. arc will start sending out error messages in next", TimeValidity/3600, "hours") |
| 54 | + } |
| 55 | + next.ServeHTTP(w, r) |
| 56 | + } else { |
| 57 | + // Write an error and stop the handler chain |
| 58 | + http.Error(w, "payment required", http.StatusPaymentRequired) |
| 59 | + } |
| 60 | + }) |
| 61 | +} |
| 62 | + |
| 63 | +func ReportUsageRequest(arcUsage ArcUsage) (ArcUsageResponse, error) { |
| 64 | + response := ArcUsageResponse{} |
| 65 | + url := "https://accapi.appbase.io/arc/" + arcUsage.ArcID + "/report_usage" |
| 66 | + marshalledRequest, err := json.Marshal(arcUsage) |
| 67 | + if err != nil { |
| 68 | + log.Println("error while marshalling req body: ", err) |
| 69 | + return response, err |
| 70 | + } |
| 71 | + req, _ := http.NewRequest("POST", url, bytes.NewBuffer(marshalledRequest)) |
| 72 | + req.Header.Add("Content-Type", "application/json") |
| 73 | + req.Header.Add("cache-control", "no-cache") |
| 74 | + |
| 75 | + res, err := http.DefaultClient.Do(req) |
| 76 | + if err != nil { |
| 77 | + log.Println("error while sending request: ", err) |
| 78 | + return response, err |
| 79 | + } |
| 80 | + defer res.Body.Close() |
| 81 | + body, err := ioutil.ReadAll(res.Body) |
| 82 | + if err != nil { |
| 83 | + log.Println("error reading res body: ", err) |
| 84 | + return response, err |
| 85 | + } |
| 86 | + err = json.Unmarshal(body, &response) |
| 87 | + |
| 88 | + if err != nil { |
| 89 | + log.Println("error while unmarshalling res body: ", err) |
| 90 | + return response, err |
| 91 | + } |
| 92 | + return response, nil |
| 93 | +} |
| 94 | + |
| 95 | +func ReportUsage() { |
| 96 | + url := os.Getenv(envEsURL) |
| 97 | + if url == "" { |
| 98 | + log.Fatalln("ES_CLUSTER_URL not found") |
| 99 | + } |
| 100 | + arcID := os.Getenv(arcIdentifier) |
| 101 | + if url == "" { |
| 102 | + log.Fatalln("ARC_ID not found") |
| 103 | + } |
| 104 | + email := os.Getenv(emailID) |
| 105 | + if url == "" { |
| 106 | + log.Fatalln("EMAIL not found") |
| 107 | + } |
| 108 | + subID := os.Getenv(subscriptionID) |
| 109 | + if url == "" { |
| 110 | + log.Println("SUBSCRIPTION_ID not found. Initializing in trial mode") |
| 111 | + } |
| 112 | + nodeCount, err := FetchNodeCount(url) |
| 113 | + if err != nil || nodeCount == -1 { |
| 114 | + log.Println("unable to fetch node count: ", err) |
| 115 | + } |
| 116 | + usageBody := ArcUsage{} |
| 117 | + usageBody.ArcID = arcID |
| 118 | + usageBody.Email = email |
| 119 | + usageBody.SubscriptionID = subID |
| 120 | + usageBody.Timestamp = time.Now().Unix() |
| 121 | + usageBody.Quantity = nodeCount |
| 122 | + response, err := ReportUsageRequest(usageBody) |
| 123 | + if err != nil { |
| 124 | + log.Println("please contact support. Usage not getting reported: ", err) |
| 125 | + } |
| 126 | + |
| 127 | + TimeValidity = response.TimeValidity |
| 128 | + if response.WarningMsg != "" { |
| 129 | + log.Println("warning:", response.WarningMsg) |
| 130 | + } |
| 131 | + if response.ErrorMsg != "" { |
| 132 | + log.Println("error:", response.ErrorMsg) |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +func FetchNodeCount(url string) (int, error) { |
| 137 | + ctx := context.Background() |
| 138 | + // Initialize the client |
| 139 | + client, err := elastic.NewClient( |
| 140 | + elastic.SetURL(url), |
| 141 | + elastic.SetRetrier(NewRetrier()), |
| 142 | + elastic.SetSniff(false), |
| 143 | + elastic.SetHttpClient(HTTPClient()), |
| 144 | + ) |
| 145 | + if err != nil { |
| 146 | + log.Fatalln("unable to initialize elastic client: ", err) |
| 147 | + } |
| 148 | + nodes, err := client.NodesInfo(). |
| 149 | + Metric("nodes"). |
| 150 | + Do(ctx) |
| 151 | + if err != nil { |
| 152 | + return -1, err |
| 153 | + } |
| 154 | + return len(nodes.Nodes), nil |
| 155 | +} |
0 commit comments