Coder Social home page Coder Social logo

opsgenie-go-sdk-v2's Introduction

opsgenie-go-sdk-v2's People

Contributors

0x46616c6b avatar arjunrajpal avatar axdotl avatar celalemre avatar cglrkn avatar dekunite avatar djmgit avatar emelkomurcu avatar erenkizilay avatar erenkzly avatar faziletozer avatar fnuva avatar frknyldz avatar garimadamani avatar ilteristabak avatar janhorstmann avatar jaseertk avatar koushik-swaminathan avatar meralbusratekinsen avatar metehanozturk avatar mjtrangoni avatar msg4sunny avatar multani avatar prakhar-mudaiya avatar rdoorn avatar rjain3-og avatar rohit-h avatar sbuyukcelebi avatar shric avatar trabab avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

opsgenie-go-sdk-v2's Issues

Cannot define immediate notification in notification rule step

I want to define a notification rule step for a "New Alert" with no delay (so that I immediately receive the notification). The Opsgenie API documentation indicates that the sendAfter field must be specified for New Alert and Assigned Alert notification rules:

Time period (in minute) when notification will be sent after. Valid and Mandatory only for New Alert and Assigned Alert notification rules. sendAfter parameter should be given as an object which has a timeAmount field that takes amount as minutes.

Nevertheless, specifying 0 as TimeAmount won't work because the field would be omitted:

type SendAfter struct {
	TimeAmount uint32 `json:"timeAmount,omitempty"`
	TimeUnit   string `json:"timeUnit,omitempty"`
}

On the other hand, the API is perfectly happy to receive 0.

Would simply removing omitempty be a viable solution?

CloudQuery Source Plugin?

Hi Team, hopefully this is right place to ask, if not, I'd appreciate if you can direct me.

I'm the founder of cloudquery.io, a high performance open source ELT framework.

Our users are interested in a OpsGenie plugin, but as we cannot maintain all the plugins ourselves, I was curious if this would be an interesting collaboration, where we would help implement an initial source plugin, and you will help maintain it.

This will give your users the ability to sync OpsGenie data to any of their datalakes/data-warehouses/databases easily using any of the growing list of CQ destination plugins.

Best,
Yevgeny

Create alert with Responders and VisibleTo not working

Hi all,

I have some questions:

  • Is this Responders and VisibleTo need extra configuration in opsgenie side?
  • Is this only an option for advanced plans?
  • Is there any extra documentation about how to create an alert using this golang sdk that shows how to write the code?

Description

Following this opsgenie documentation I'm trying to add both fields in alert creation:

...
createResult, err := alertClient.Create(ctx, &alert.CreateAlertRequest{
		Message:     title,
		Alias:       alias,
		Description: something,
		Responders:  teams,
		VisibleTo:   visibilityTeams,
		...

in teams variable:

[]alert.Responder{alert.Responder{Type:"team", Name:"ops", Id:"", Username:""},}

in visibilityTeams:

[]alert.Responder{alert.Responder{Type:"team", Name:"sre", Id:"", Username:""},}

But when I checked in my opsgenie free account logs, it doesn't work (only responders):

_incomingData
_parsedData
note null
-responders
0 ops
-actions [ ]
-tags [ webserver01, check-nginx, default, agent ]
alias webserver01/check-nginx
description example output
source sensuGo
message webserver01/check-nginx
priority P5
user Alert API
_extraProperties { subscriptions: [testing], interval: 20, status: 1 }
entity webserver01
integrationType Sensu
integrationName ops_Sensu

Why in incomingData.parsedData there's no visibleTo field?

I'm trying to add this option in my sensu opsgenie plugin
And I'm using sensu integration to grant me an API key.

Thanks for any help.

Logrus related compile time error

# github.com/moira-alert/moira/vendor/github.com/opsgenie/opsgenie-go-sdk-v2/client
vendor/github.com/opsgenie/opsgenie-go-sdk-v2/client/client.go:179:14: conf.Logger.SetFormatter undefined (type *logrus.Logger has no field or method SetFormatter)
vendor/github.com/opsgenie/opsgenie-go-sdk-v2/client/client.go:249:23: client.Config.Logger.GetLevel undefined (type *logrus.Logger has no field or method GetLevel)
vendor/github.com/opsgenie/opsgenie-go-sdk-v2/client/config.go:90:14: undefined: logrus.TraceLevel

I am getting the above error when trying to complie code that uses the github.com/opsgenie/opsgenie-go-sdk-v2/client package. I am using govendor to vendor my dependencies. Any ideas on what might be the issue?

Update integration fails with error - "You can not assign integration to another team"

Hi,
I am getting the following error while trying to update an integration.

{"code":40301,"message":"You can not assign integration to another team","took":0.002,"requestId":"2986a890-3fd3-4f5e-973b-4e6034c5936a"}

I think this could be due to a bug in the function 'ForceUpdateAllFields'

https://github.com/opsgenie/opsgenie-go-sdk-v2/blob/v1.1/integration/integration.go#L57

There we can see that it's not passing the 'OwnerTeam' argument to the request. And in my trial runs using curl, I found that if I try to update an integration without passing the 'ownerTeam' argument in the JSON payload, it will result in the same error.

curl -X PUT 'https://api.eu.opsgenie.com/v2/integrations/<integration_id>' --header 'Authorization: GenieKey<API_KEY>' --header 'Content-Type: application/json' --data '{ "enabled": true, "ignoreRespondersFromPayload": true, "name": "<INTEGRATION_NAME>", "suppressNotifications": true, "responders": [], "type": "API" }'

{"code":40301,"message":"You can not assign integration to another team","took":0.002,"requestId":"2986a890-3fd3-4f5e-973b-4e6034c5936a"}

Please note I am using an API key from an API integration which I have created under my 'team' to authenticate the SDK to OpsGenie. Could that be an issue?

No field for url in APIBasedIntegrationRequest

In order to create api integration of type Webhook the REST API excpects a url field which will basically contain the endpoint where Opsgenie will make requests on alerts. However this field is currently not mentioned in APIBasedIntegrationRequest. As a result, the sdk cannot create Webhook integrations

Fail to create a disabled Heartbeat

I think this is similar to #11, when I create a new heartbeat.AddRequest with Enabled: false, the JSON Marshaller drops the field from the returned JSON, which in results in a payload rejection from the API, leading to this error:

ERRO[2019-09-10T11:24:44.601831+01:00] Error occurred with Status code: 422, Message: Request body is not processable. Please check the errors., Took: 0.029000, RequestId: cd7bec9b-......, Error Detail: map[enabled:may not be null] 

I believe this is the intended behaviour of the Go JSON Marshaller because the struct definition has omitempty for that field.

Ability to disable logging

Hi,

right now, due to:

func printInfoLog(client *OpsGenieClient) {Eren Kızılay, 3 years ago: • design change
	client.Config.Logger.Infof("Client is configured with ApiUrl: %s, LogLevel: %s, RetryMaxCount: %v",
		client.Config.OpsGenieAPIURL,
		client.Config.Logger.GetLevel().String(),
		client.RetryableClient.RetryMax)
}

any client connection gets logged - this can be very verbose in downstream user logs]

this is what we see in all pulumi runs

Previewing update (test):
     Type                 Name       Plan     Info
     pulumi:pulumi:Stack  test                1 message

Diagnostics:
  pulumi:pulumi:Stack (test):
    INFO[2021-07-13T16:52:34.811336306+01:00] Client is configured with ApiUrl: api.opsgenie.com, LogLevel: info, RetryMaxCount: 10

Paul

Non-idiomatic Time Format Used

For some reason, the time format 2006-01-02T15:04:05.000Z is used instead of the idiomatic time.RFC3339 or time.RFC3339Nano.

This does not work well for different time zones or daylights saving time (playground link).

Possible fixes:

  • One solution would be to change the format to time.RFC3339Nano. It is unclear if API can handle the different format.
  • We should at least make sure that the time is set to the UTC location: #113

Postmortem API

Hi,

It seems that Postmortem API is not implemented in Go SDK.
On top of that, there is no way to get a postmortem that is linked to an incident via the REST API.
I took a quick look at the API that is being used by the portal itself, and it seems that this postmortem info is present under /:incidentId/details, as well as in the general list.
Can this be exposed in the Rest API as well?

Service result struct missing links property

I notice the GET Service API is returning information we want to retrieve in our application that the current result struct does not retain. Ex:

curl -X GET 'https://api.opsgenie.com/v1/services/:service_id' \
    -H 'Authorization: GenieKey ...' \
    -H 'Content-Type: application/json' | json_pp
{
   "data" : {
      "description" : "test",
      "id" : "${service_id}",
      "isExternal" : false,
      "links" : {
         "api" : "...",
         "web" : "..."
      },
      "name" : "test",
      "tags" : [],
      "teamId" : "..."
   },
   "requestId" : "...",
   "took" : 0.005
}

In my application I'd like to retrieve links property but the result struct doesn't decode this.

Current workaround:

  • send requests to the API instead of using the sdk

Possible fix:

  • define a Links struct with the same properties api and web that can decode this json
  • Add the Links struct as a property to the Service struct such that GET service responses will decode this information correctly

Policy/request.go has faulty DelayAction struct.

Here:

UntilMinute int `json:"untilMinute,omitempty"`

is a bug, following struct is configured:

type DelayAction struct {
        DelayOption DelayType `json:"delayOption,omitempty"`
        UntilMinute int       `json:"untilMinute,omitempty"`
        UntilHour   int       `json:"untilHour,omitempty"`
        Duration    *Duration `json:"duration,omitempty"`
}

Problem is that if UntilMinute and / or UntilHour is 0 then argument is omitted as it's seen as empty (which in this case is not the case).
Due to this issue it's not possible to set any of those to 0.
According to: https://www.sohamkamani.com/blog/golang/2018-07-19-golang-omitempty/

Solution would be to switch field to:

 *int 

So, struct would look like that:

type DelayAction struct {
        DelayOption DelayType `json:"delayOption,omitempty"`
        UntilMinute *int       `json:"untilMinute,omitempty"`
        UntilHour   *int       `json:"untilHour,omitempty"`
        Duration    *Duration `json:"duration,omitempty"`
}

Zero StartMin, EndMin omitempty on Restriction

Hei, i'm trying to use create rotation (with time restrict) from the sdk. But there error:
Error occurred with Status code: 422, Message: Request body is not processable. Please check the errors., Took: 0.005000, RequestId: efeac8ca-a11f-4e5d-aceb-5eb3ca8cefab, Error Detail: map[endMin:may not be null startMin:may not be null]

I set the restrict StartMin, and EndMin to 0. But i think it was omitted by json: omitempty.
I think the StartMin, and EndMin should not set as omitempty, because it makes no value when requesting to the opsgenie api.

I think, we must change / remove the omitempty tags of StartMin and EndMin on Restriction struct

Thanks!

Could not set requestId

We're getting a lot of warnings for Could not set requestId.

It seems to be coming from this line https://github.com/opsgenie/opsgenie-go-sdk-v2/blob/master/client/client.go#L149

Below is a sample of a response not containing the requestId as logged by this line https://github.com/opsgenie/opsgenie-go-sdk-v2/blob/master/client/client.go#L501 :

time=2022/10/31 08:50:01 level=debug msg=Request processed. The result: &{ResultMetadata:{RequestId: ResponseTime:0.031 RateLimitState:OK RateLimitReason: RateLimitPeriod: RetryCount:0} Parent:{Id:a3f182a3-7860-40da-9832-d238cbe6d3aa Name:TEST_TEAM_schedule Enabled:true} OnCallParticipants:[] OnCallRecipients:[]}

The endpoint in question is https://docs.opsgenie.com/docs/who-is-on-call-api#get-on-calls for the above log entry

Vendored dependency for logrus

Hi all,

according to the Opsgenie docs, there is the possibility to control the LogLevel while initializing the api client.

But sadly, the used logrus is a vendored dependency for OpsGenie.

  • using import "github.com/opsgenie/opsgenie-go-sdk-v2/vendor/github.com/sirupsen/logrus" fails because, it's a vendored dependency
  • using import "import "github.com/sirupsen/logrus" fails, because the types for LogLevel won't match.

So, there is no currently possibility to pass LogLevel to the opsgenie golang library.

I'm a golang freshman and I don't understand the concept of vendored dependencies and especially their design decisions.

But I see a few ways to proceed:

  • Remove logrus from the vendor directory in the opsgenie API. According to my tests, this works fine.
  • Hide the vendored logrus (and pass LogLevel types from the opsgenie API).
  • Do some weird hacking in the GOPATH mv $GOPATH/src/github.com/opsgenie/opsgenie-go-sdk-v2/vendor/github.com/sirupsen $GOPATH/src/github.com (but this can't be the solution)
  • ? something else

What is the favorite way to solve this problem and be able to pass a LogLevel to the api client?

API Key is leaked when a client is created

Currently when a client is created it prints a log, this contains information about the API Key and other client details.

Ideally this wouldn't be logged at all and would be left up to the consuming application, but there are security implications by automatically logging the API key that is leaked into whatever log aggregation when the client is created, without anyway to disable this.

#6

ndefined: logrus.TraceLevel && multiple-value uuid.NewV4() in single-value context

Trying to run the below example from the OpsGenie site:
https://docs.opsgenie.com/docs/opsgenie-go-api-v2

package main

import (
	"fmt"

	"github.com/opsgenie/opsgenie-go-sdk-v2/alert"
	"github.com/opsgenie/opsgenie-go-sdk-v2/client"
	"github.com/opsgenie/opsgenie-go-sdk-v2/policy"
)

func main() {

	//create a policy client
	policyClient, err := policy.NewClient(&client.Config{ApiKey: "your api key"})

	if err != nil {
		fmt.Println("error occured while creating policy client")
		return
	}

	//create a request object
	createAlertPolicyRequest := &policy.CreateAlertPolicyRequest{
		MainFields: policy.MainFields{
			Name:              "my alert policy",
			Enabled:           false,
			PolicyDescription: "a policy",
		},
		Message:  "a message",
		Continue: false,
		Alias:    "an alias",
		Priority: alert.P1,
	}

	//function call to process the request
	createAlertPolicyResult, err := policyClient.CreateAlertPolicy(nil, createAlertPolicyRequest)

	if err != nil {
		fmt.Printf("error: %s\n", err)
	} else {
		fmt.Sprintf("result: %v+: ", createAlertPolicyResult)
	}

}

Getting the following error

../../go/src/github.com/opsgenie/opsgenie-go-sdk-v2/client/config.go:90:14: undefined: logrus.TraceLevel
../../go/src/github.com/opsgenie/opsgenie-go-sdk-v2/client/metric.go:104:29: multiple-value uuid.NewV4() in single-value context

List Schedule not contains Id for Rotation

Hello, I have a personal problem when using this sdk :(.
My case, i need to use List Schedule from the sdk. I need to get the detail of each rotation on each schedule, but there lack of field i needed from the rotation field. I need the Id attribute of the rotation from List Schedule result.

From Rotations type using og.Rotation that not contain Id Rotation. So Rotation from List Schedule result will not contain the Id of Rotation, but i need it :(.

From this api documentation, the rest api for list schedule rotation contains the id rotation. I think all we need is to add an Id field in og.Rotation, so the schedule result always contains Rotation Id's.

My solution purpose is to change this lines to :

type Rotation struct {
	client.BaseRequest
	Id              string           `json:"id,omitempty"`
	Name            string           `json:"name,omitempty"`
	StartDate       *time.Time       `json:"startDate,omitempty"`
	EndDate         *time.Time       `json:"endDate,omitempty"`
	Type            RotationType     `json:"type,omitempty"`
	Length          uint32           `json:"length,omitempty"`
	Participants    []Participant    `json:"participants,omitempty"`
	TimeRestriction *TimeRestriction `json:"timeRestriction,omitempty"`
}

I hope you can consider my problem and my propose solution.

Thanks :)

`service_incident_rule` uses ServiceId as required string, not array

Context

When creating a team's incident ruleset via API we currently must use service ID as a string. This must be a valid Id as well (as seen in the validation section).

When trying to create the team incident ruleset via web however, we notice we can add multiple services to a ruleset. This allows us to state "when alert X comes with data Y, we know service A and B are down!" Similarly through an empty array, we could declare a generic incident that can mark high priority alerts without immediately specifying impact.

Symptoms

  • Creating Incidents from Alerts becomes severely restricted in a programmatic manner.
  • Terraform Provider Runs into the exact same issue [docs]

References:

{
 "incidentRuleDto": {
   "id": "",
   "name": null,
   "description": null,
   "order": null,
   "serviceIds": [],
   ...

Solution

We need an update such that the ServiceId is an array and brought up to web API versions structure.

How to get the ID of a newly created alert

I am creating an alert with the alertClient.Create() function https://docs.opsgenie.com/docs/opsgenie-go-api-v2#create-alert.

How can I get the ID of the newly created alert? Currently, I am setting a self-generated ID as alias and then query the alert with the alias ID to get the alert ID. Is there a way to directly get the ID of the alert, or is this not possible as the alert is created async in the background?

The response object with the type alert.AsyncAlertResult only contains a request ID. Is there a way to get the alert ID with the request ID?

An empty TimeRestriction struct does not result in an empty JSON object "{}"

The TimeRestriction struct is defined in og/entity.go as:

type TimeRestriction struct {
	Type            RestrictionType `json:"type,omitempty"`
	RestrictionList []Restriction   `json:"restrictions,omitempty"`
	Restriction     Restriction     `json:"restriction,omitempty"`
}

When an empty TimeRestriction is created and encoding/json is used to encode the struct into JSON, the resulting JSON is an object with a restriction: {} field. A very basic example is:

package main

import (
	"fmt"
	"encoding/json"

	"github.com/opsgenie/opsgenie-go-sdk-v2/og"
)

func main() {
	time_restriction := og.TimeRestriction{}
	b, _ := json.Marshal(time_restriction)
	fmt.Println(string(b))
}

Result:

{"restriction":{}}

This expected result should be an empty JSON object (i.e., {}).

This is preventing me from using the OpsGenie Go SDK to remove a time restriction from an existing schedule rotation. I'm wanting to use schedule.UpdateRotation() with an UpdateRotationRequest that includes an empty time restriction within the rotation definition. The UpdateRotationRequest.Rotation.TimeRestriction field cannot be a nil pointer, as this would result in the time restriction not being updated at all. It needs to have a zero value so that it results in an empty map when it's converted to JSON in the HTTP request body.

I think the solution is to redefine the TimeRestriction struct with the TimeRestriction.Restriction field as a pointer:

type TimeRestriction struct {
	Type            RestrictionType `json:"type,omitempty"`
	RestrictionList []Restriction   `json:"restrictions,omitempty"`
	Restriction     *Restriction     `json:"restriction,omitempty"`
}

A zero-value TimeRestriction in this case results in an empty JSON object, which would allow for a time restriction to be removed using schedule.UpdateRotation().

I don't know what implications this has on the rest of the code base though.

Do not log 404 errors

Hello,

I have a workflow where I try to get an OpsGenie alert by alias to check existence and close it if needed.
Whenever I get an alert that does not exist on OpsGenie, SDK logs an error-level message on API 404 error.
This creates many error-level logs on my application despite everything working as expected.

Here is the culprit: https://github.com/opsgenie/opsgenie-go-sdk-v2/blob/master/client/client.go#L475

I want to remove this log because it is not an actual API error, and leave it to the caller to decide to log this information.

Thanks

Issue with vendor module sys/unix

When I wrote the code using the SDK I got error messages.

# github.com/opsgenie/opsgenie-go-sdk-v2/vendor/golang.org/x/sys/unix
../../golang/src/github.com/opsgenie/opsgenie-go-sdk-v2/vendor/golang.org/x/sys/unix/syscall_darwin.1_13.go:29:3: //go:linkname must refer to declared function or variable
../../golang/src/github.com/opsgenie/opsgenie-go-sdk-v2/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.1_13.go:27:3: //go:linkname must refer to declared function or variable
../../golang/src/github.com/opsgenie/opsgenie-go-sdk-v2/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.1_13.go:40:3: //go:linkname must refer to declared function or variable
../../golang/src/github.com/opsgenie/opsgenie-go-sdk-v2/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go:28:3: //go:linkname must refer to declared function or variable
../../golang/src/github.com/opsgenie/opsgenie-go-sdk-v2/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go:43:3: //go:linkname must refer to declared function or variable
../../golang/src/github.com/opsgenie/opsgenie-go-sdk-v2/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go:59:3: //go:linkname must refer to declared function or variable
../../golang/src/github.com/opsgenie/opsgenie-go-sdk-v2/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go:75:3: //go:linkname must refer to declared function or variable
../../golang/src/github.com/opsgenie/opsgenie-go-sdk-v2/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go:90:3: //go:linkname must refer to declared function or variable
../../golang/src/github.com/opsgenie/opsgenie-go-sdk-v2/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go:105:3: //go:linkname must refer to declared function or variable
../../golang/src/github.com/opsgenie/opsgenie-go-sdk-v2/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go:121:3: //go:linkname must refer to declared function or variable
../../golang/src/github.com/opsgenie/opsgenie-go-sdk-v2/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go:121:3: too many errors

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.