Skip to content

Commit

Permalink
Subaccounts support and overall refactoring (#64)
Browse files Browse the repository at this point in the history
* SubAccountCreate

Signed-off-by: yyyogev <[email protected]>

* jonboydell -> logzio

Signed-off-by: yyyogev <[email protected]>

* package global createHttpRequest

Signed-off-by: yyyogev <[email protected]>

* remake missing commit

Signed-off-by: yyyogev <[email protected]>

* use global CreateHttpRequest

Signed-off-by: yyyogev <[email protected]>

* handle null utilization settings

Signed-off-by: yyyogev <[email protected]>

* logging

Signed-off-by: yyyogev <[email protected]>

* adjust subaccount to match responses

Signed-off-by: yyyogev <[email protected]>

* remove email and token

Signed-off-by: yyyogev <[email protected]>

* remove nulls from read response

Signed-off-by: yyyogev <[email protected]>

* add delete user status code 204

Signed-off-by: yyyogev <[email protected]>

* remove wrong validation

Signed-off-by: yyyogev <[email protected]>

* add endpoint create 204 status code

Signed-off-by: yyyogev <[email protected]>

* 200 -> statuscode ok

Signed-off-by: yyyogev <[email protected]>

* remove circle CI

Signed-off-by: yyyogev <[email protected]>

* jonboydell -> logzio

Signed-off-by: yyyogev <[email protected]>

* remove redundant fields

Signed-off-by: yyyogev <[email protected]>

* subaccounts doc

Signed-off-by: yyyogev <[email protected]>

* remove workflow

Signed-off-by: yyyogev <[email protected]>

* find account id link

Signed-off-by: yyyogev <[email protected]>

* support tags in alerts

Signed-off-by: yyyogev <[email protected]>

* test tags in alerts

Signed-off-by: yyyogev <[email protected]>

* refactor endpoints http requests

Signed-off-by: yyyogev <[email protected]>

* refactor get endpoint request

Signed-off-by: yyyogev <[email protected]>

* refactor users requests

Signed-off-by: yyyogev <[email protected]>
  • Loading branch information
yyyogev authored Aug 9, 2020
1 parent 6996ff9 commit 5bf74cf
Show file tree
Hide file tree
Showing 66 changed files with 373 additions and 401 deletions.
43 changes: 0 additions & 43 deletions .circleci/config.yml

This file was deleted.

28 changes: 0 additions & 28 deletions .github/workflows/go.yml

This file was deleted.

2 changes: 0 additions & 2 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
MIT License

Copyright (c) 2018 jonboydell

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
Expand Down
68 changes: 52 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,13 @@
# Logz.io Terraform client library

DEVELOP - [![Build Status](https://travis-ci.org/jonboydell/logzio_client.svg?branch=develop)](https://travis-ci.org/jonboydell/logzio_client) [![Coverage Status](https://coveralls.io/repos/github/jonboydell/logzio_client/badge.svg?branch=develop)](https://coveralls.io/github/jonboydell/logzio_client?branch=develop)

MASTER - [![Build Status](https://travis-ci.org/jonboydell/logzio_client.svg?branch=master)](https://travis-ci.org/jonboydell/logzio_client)

Client library for logz.io API, see below for supported endpoints.
Client library for Logz.io API, see below for supported endpoints.

The primary purpose of this library is to act as the API interface for the logz.io Terraform provider.

Logz.io have not written an especially consistent API. Sometimes, JSON will be presented back from an API call, sometimes not. Sometimes just a status code, sometimes a 200 status code, but with an error message in the body. I have attempted to shield the user of this library from those inconsistencies, but as they are laregely not documented, it's pretty diffcult to know if I've got them all.

[Roadmap](#roadmap)
To use it, you'll need to [create an API token](https://app.logz.io/#/dashboard/settings/api-tokens) and provide it to the client library along with your logz.io regional [API server address](https://docs.logz.io/user-guide/accounts/account-region.html#regions-and-urls).

##### Usage

Note: the lastest version of the API (1.1) is not backwards compatible with previous versions, specifically the client entrypoint names have changed to prevent naming conflicts. Use `UsersClient` ([Users API](#users)) , `AlertsClient` ([Alerts API](#alerts)) and `EndpointsClient` ([Endpoints API](#endpoints)) rather than `Users`, `Alerts` and `Endpoints`.
Note: the lastest version of the API (1.3) is not backwards compatible with previous versions, specifically the client entrypoint names have changed to prevent naming conflicts. Use `UsersClient` ([Users API](#users)) ,`SubaccountClient` ([Sub-accounts API](#sub-accounts)), `AlertsClient` ([Alerts API](#alerts)) and `EndpointsClient` ([Endpoints API](#endpoints)) rather than `Users`, `Alerts` and `Endpoints`.


##### Alerts
Expand All @@ -24,8 +17,8 @@ To create an alert where the type field = 'mytype' and the loglevel field = ERRO
https://support.logz.io/hc/en-us/articles/209487329-How-do-I-create-an-Alert-

```go
client, _ := alerts.New(apiToken)
client.CreateAlert(alerts.CreateAlertType{
client, _ := alerts.New(apiToken, apiServerAddress)
alert := client.CreateAlert(alerts.CreateAlertType{
Title: "this is my alert",
Description: "this is my description",
QueryString: "loglevel:ERROR",
Expand Down Expand Up @@ -59,10 +52,10 @@ client.CreateAlert(alerts.CreateAlertType{

##### Users

To create a new user, on a specific account or sub-account (you can get your account id from the logz.io console)
To create a new user, on a specific account or sub-account. you'll need [your account Id](https://docs.logz.io/user-guide/accounts/finding-your-account-id.html).

```go
client, _ := users.New(apiToken)
client, _ := users.New(apiToken, apiServerAddress)
user := client.User{
Username: "[email protected]",
Fullname: "my username",
Expand All @@ -81,11 +74,47 @@ user := client.User{
|suspend user|`func (c *UsersClient) SuspendUser(userId int32) (bool, error)`|
|unsuspend user|`func (c *UsersClient) UnSuspendUser(userId int32) (bool, error)`|

##### Sub-accounts

To create a new sub-account, on a main account.
```go
client, _ := sub_accounts.New(apiToken, apiServerAddress)
subaccount := sub_accounts.SubAccountCreate{
Email: "[email protected]",
AccountName: "my account name",
MaxDailyGB: 6.5,
RetentionDays: 4,
Searchable: true,
Accessible: false,
SharingObjectAccounts: []int32{accountId1, accountId2}, //Id's of the accounts who will be able to access this account
DocSizeSetting: true,
}
```

|function|func name|
|---|---|
|create sub-account|`func (c *SubAccountClient) CreateSubAccount(subAccount SubAccountCreate) (*SubAccount, error) `|
|update sub-account|`func (c *SubAccountClient) UpdateSubAccount(id int64, subAccount SubAccount) error`|
|delete sub-account|`func (c *SubAccountClient) DeleteSubAccount(id int64) error`|
|get sub-account|`func (c *SubAccountClient) GetSubAccount(id int64) (*SubAccount, error)`|
|get detailed sub-account|`func (c *SubAccountClient) GetDetailedSubAccount(id int64) (*SubAccountDetailed, error)`|
|list sub-accounts|`func (c *SubAccountClient) ListSubAccounts() ([]SubAccount, error)`|
|list detailed sub-accounts|`func (c *SubAccountClient) DetailedSubAccounts() ([]SubAccountDetailed, error) `|

##### Endpoints

There's no 1-1 mapping between this library and the logz.io API functions, logz.io provide one API endpoint per *type* of notification endpoint being created. I have abstracted this so that depending on how you create your `Endpoints` variable that you pass to `CreateEndpoint` the `CreateEndpoint` function will work out which API call to make.
For each type of endpoint there is a different structure, below you can find an example for creating a Slack endpoint.
For more info, see: https://docs.logz.io/api/#tag/Manage-notification-endpoints or check our endpoints tests for more examples.

For more info, see: https://docs.logz.io/api/#tag/Manage-notification-endpoints
```go
client, _ := endpoints.New(apiToken, apiServerAddress)
endpoint, err := underTest.CreateEndpoint(endpoints.Endpoint{
Title: "some_endpoint",
Description: "my description",
Url: "https://this.is.com/some/webhook",
EndpointType: endpoints.EndpointTypeSlack,
})
```

#### Contributing

Expand All @@ -96,4 +125,11 @@ For more info, see: https://docs.logz.io/api/#tag/Manage-notification-endpoints
`go test -v -race ./...`


### Changelog
- v1.3
- unnecessary resource updates bug fix.
- support tags in alerts
- v1.2
- Add subaccount support


4 changes: 2 additions & 2 deletions alerts/alerts_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package alerts_test

import (
"github.com/jonboydell/logzio_client/alerts"
"github.com/jonboydell/logzio_client/test_utils"
"github.com/logzio/logzio_terraform_client/alerts"
"github.com/logzio/logzio_terraform_client/test_utils"
"io/ioutil"
"net/http"
"net/http/httptest"
Expand Down
11 changes: 10 additions & 1 deletion alerts/client_alerts.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package alerts
import (
"fmt"

"github.com/jonboydell/logzio_client/client"
"github.com/logzio/logzio_terraform_client/client"
)

const (
Expand Down Expand Up @@ -53,6 +53,7 @@ const (
fldTitle string = "title"
fldValueAggregationField string = "valueAggregationField"
fldValueAggregationType string = "valueAggregationType"
fldTags string = "tags"
)

type CreateAlertType struct {
Expand All @@ -70,6 +71,7 @@ type CreateAlertType struct {
Title string
ValueAggregationField interface{}
ValueAggregationType string
Tags []string
}

type AlertType struct {
Expand All @@ -94,6 +96,7 @@ type AlertType struct {
Title string
ValueAggregationField interface{}
ValueAggregationType string
Tags []string
}

type SeverityThresholdType struct {
Expand All @@ -118,6 +121,7 @@ func jsonAlertToAlert(jsonAlert map[string]interface{}) AlertType {
Threshold: int(jsonAlert[fldThreshold].(float64)),
Title: jsonAlert[fldTitle].(string),
ValueAggregationType: jsonAlert[fldValueAggregationType].(string),
Tags: []string{},
}

if jsonAlert[fldGroupByAggregationFields] != nil {
Expand All @@ -136,6 +140,11 @@ func jsonAlertToAlert(jsonAlert map[string]interface{}) AlertType {
alert.LastTriggeredAt = jsonAlert[fldLastTriggeredAt].(interface{})
}

tags := jsonAlert[fldTags].([]interface{})
for _, tag := range tags {
alert.Tags = append(alert.Tags, tag.(string))
}

tiers := jsonAlert[fldSeverityThresholdTiers].([]interface{})
for x := 0; x < len(tiers); x++ {
tier := tiers[x].(map[string]interface{})
Expand Down
27 changes: 6 additions & 21 deletions alerts/client_alerts_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,14 @@ import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"

"github.com/jonboydell/logzio_client"
"github.com/jonboydell/logzio_client/client"
"github.com/logzio/logzio_terraform_client"
)

const createAlertServiceUrl string = alertsServiceEndpoint
const createAlertServiceMethod string = http.MethodPost
const createAlertMethodSuccess int = 200
const createAlertMethodSuccess int = http.StatusOK

type FieldError struct {
Field string
Expand Down Expand Up @@ -61,8 +59,8 @@ func validateCreateAlertRequest(alert CreateAlertType) error {
}
}

if AggregationTypeNone == alert.ValueAggregationType && (alert.ValueAggregationField != nil || alert.GroupByAggregationFields != nil) {
message := fmt.Sprintf("if ValueAggregaionType is %s then ValueAggregationField and GroupByAggregationFields must be nil", AggregationTypeNone)
if AggregationTypeNone == alert.ValueAggregationType && (alert.ValueAggregationField != nil) {
message := fmt.Sprintf("if ValueAggregaionType is %s then ValueAggregationField must be nil", AggregationTypeNone)
return FieldError{"valueAggregationTypeComposite", message}
}

Expand All @@ -87,6 +85,7 @@ func buildCreateAlertRequest(alert CreateAlertType) map[string]interface{} {
createAlert[fldTitle] = alert.Title
createAlert[fldValueAggregationField] = alert.ValueAggregationField
createAlert[fldValueAggregationType] = alert.ValueAggregationType
createAlert[fldTags] = alert.Tags
return createAlert
}

Expand All @@ -112,27 +111,13 @@ func (c *AlertsClient) CreateAlert(alert CreateAlertType) (*AlertType, error) {

createAlert := buildCreateAlertRequest(alert)
req, _ := c.buildCreateApiRequest(c.ApiToken, createAlert)

httpClient := client.GetHttpClient(req)
resp, err := httpClient.Do(req)
jsonResponse, err := logzio_client.CreateHttpRequest(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()

jsonBytes, _ := ioutil.ReadAll(resp.Body)
if !logzio_client.CheckValidStatus(resp, []int{createAlertMethodSuccess}) {
return nil, fmt.Errorf("API call %s failed with status code %d, data: %s", "CreateAlert", resp.StatusCode, jsonBytes)
}

var jsonResponse map[string]interface{}
err = json.Unmarshal(jsonBytes, &jsonResponse)

retVal := jsonAlertToAlert(jsonResponse)

if err != nil {
return nil, err
}

return &retVal, nil
}
6 changes: 3 additions & 3 deletions alerts/client_alerts_delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@ package alerts

import (
"fmt"
"github.com/jonboydell/logzio_client"
"github.com/jonboydell/logzio_client/client"
"github.com/logzio/logzio_terraform_client"
"github.com/logzio/logzio_terraform_client/client"
"io/ioutil"
"net/http"
"strings"
)

const deleteAlertServiceUrl string = alertsServiceEndpoint + "/%d"
const deleteAlertServiceMethod string = http.MethodDelete
const deleteAlertMethodSuccess int = 200
const deleteAlertMethodSuccess int = http.StatusOK

func (c *AlertsClient) buildDeleteApiRequest(apiToken string, alertId int64) (*http.Request, error) {
baseUrl := c.BaseUrl
Expand Down
6 changes: 3 additions & 3 deletions alerts/client_alerts_get.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ package alerts
import (
"encoding/json"
"fmt"
"github.com/jonboydell/logzio_client"
"github.com/jonboydell/logzio_client/client"
"github.com/logzio/logzio_terraform_client"
"github.com/logzio/logzio_terraform_client/client"
"io/ioutil"
"net/http"
"strings"
)

const getAlertServiceUrl string = alertsServiceEndpoint + "/%d"
const getAlertServiceMethod string = http.MethodGet
const getAlertMethodSuccess int = 200
const getAlertMethodSuccess int = http.StatusOK

func (c *AlertsClient) buildGetApiRequest(apiToken string, alertId int64) (*http.Request, error) {
baseUrl := c.BaseUrl
Expand Down
6 changes: 3 additions & 3 deletions alerts/client_alerts_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ package alerts
import (
"encoding/json"
"fmt"
"github.com/jonboydell/logzio_client"
"github.com/jonboydell/logzio_client/client"
"github.com/logzio/logzio_terraform_client"
"github.com/logzio/logzio_terraform_client/client"
"io/ioutil"
"net/http"
)

const listAlertServiceUrl string = alertsServiceEndpoint
const listAlertServiceMethod string = http.MethodGet
const listAlertMethodSuccess int = 200
const listAlertMethodSuccess int = http.StatusOK

func (c *AlertsClient) buildListApiRequest(apiToken string) (*http.Request, error) {
baseUrl := c.BaseUrl
Expand Down
Loading

0 comments on commit 5bf74cf

Please sign in to comment.