1// Copyright 2019 Google LLC
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//     https://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// Code generated by gapic-generator. DO NOT EDIT.
16
17package monitoring
18
19import (
20	"context"
21	"fmt"
22	"math"
23	"time"
24
25	"github.com/golang/protobuf/proto"
26	gax "github.com/googleapis/gax-go/v2"
27	"google.golang.org/api/iterator"
28	"google.golang.org/api/option"
29	"google.golang.org/api/transport"
30	monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3"
31	"google.golang.org/grpc"
32	"google.golang.org/grpc/codes"
33	"google.golang.org/grpc/metadata"
34)
35
36// AlertPolicyCallOptions contains the retry settings for each method of AlertPolicyClient.
37type AlertPolicyCallOptions struct {
38	ListAlertPolicies []gax.CallOption
39	GetAlertPolicy    []gax.CallOption
40	CreateAlertPolicy []gax.CallOption
41	DeleteAlertPolicy []gax.CallOption
42	UpdateAlertPolicy []gax.CallOption
43}
44
45func defaultAlertPolicyClientOptions() []option.ClientOption {
46	return []option.ClientOption{
47		option.WithEndpoint("monitoring.googleapis.com:443"),
48		option.WithScopes(DefaultAuthScopes()...),
49	}
50}
51
52func defaultAlertPolicyCallOptions() *AlertPolicyCallOptions {
53	retry := map[[2]string][]gax.CallOption{
54		{"default", "idempotent"}: {
55			gax.WithRetry(func() gax.Retryer {
56				return gax.OnCodes([]codes.Code{
57					codes.Unavailable,
58				}, gax.Backoff{
59					Initial:    100 * time.Millisecond,
60					Max:        60000 * time.Millisecond,
61					Multiplier: 1.3,
62				})
63			}),
64		},
65	}
66	return &AlertPolicyCallOptions{
67		ListAlertPolicies: retry[[2]string{"default", "idempotent"}],
68		GetAlertPolicy:    retry[[2]string{"default", "idempotent"}],
69		CreateAlertPolicy: retry[[2]string{"default", "non_idempotent"}],
70		DeleteAlertPolicy: retry[[2]string{"default", "idempotent"}],
71		UpdateAlertPolicy: retry[[2]string{"default", "non_idempotent"}],
72	}
73}
74
75// AlertPolicyClient is a client for interacting with Stackdriver Monitoring API.
76//
77// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
78type AlertPolicyClient struct {
79	// The connection to the service.
80	conn *grpc.ClientConn
81
82	// The gRPC API client.
83	alertPolicyClient monitoringpb.AlertPolicyServiceClient
84
85	// The call options for this service.
86	CallOptions *AlertPolicyCallOptions
87
88	// The x-goog-* metadata to be sent with each request.
89	xGoogMetadata metadata.MD
90}
91
92// NewAlertPolicyClient creates a new alert policy service client.
93//
94// The AlertPolicyService API is used to manage (list, create, delete,
95// edit) alert policies in Stackdriver Monitoring. An alerting policy is
96// a description of the conditions under which some aspect of your
97// system is considered to be "unhealthy" and the ways to notify
98// people or services about this state. In addition to using this API, alert
99// policies can also be managed through
100// Stackdriver Monitoring (at https://cloud.google.com/monitoring/docs/),
101// which can be reached by clicking the "Monitoring" tab in
102// Cloud Console (at https://console.cloud.google.com/).
103func NewAlertPolicyClient(ctx context.Context, opts ...option.ClientOption) (*AlertPolicyClient, error) {
104	conn, err := transport.DialGRPC(ctx, append(defaultAlertPolicyClientOptions(), opts...)...)
105	if err != nil {
106		return nil, err
107	}
108	c := &AlertPolicyClient{
109		conn:        conn,
110		CallOptions: defaultAlertPolicyCallOptions(),
111
112		alertPolicyClient: monitoringpb.NewAlertPolicyServiceClient(conn),
113	}
114	c.setGoogleClientInfo()
115	return c, nil
116}
117
118// Connection returns the client's connection to the API service.
119func (c *AlertPolicyClient) Connection() *grpc.ClientConn {
120	return c.conn
121}
122
123// Close closes the connection to the API service. The user should invoke this when
124// the client is no longer required.
125func (c *AlertPolicyClient) Close() error {
126	return c.conn.Close()
127}
128
129// setGoogleClientInfo sets the name and version of the application in
130// the `x-goog-api-client` header passed on each request. Intended for
131// use by Google-written clients.
132func (c *AlertPolicyClient) setGoogleClientInfo(keyval ...string) {
133	kv := append([]string{"gl-go", versionGo()}, keyval...)
134	kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version)
135	c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...))
136}
137
138// ListAlertPolicies lists the existing alerting policies for the project.
139func (c *AlertPolicyClient) ListAlertPolicies(ctx context.Context, req *monitoringpb.ListAlertPoliciesRequest, opts ...gax.CallOption) *AlertPolicyIterator {
140	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", req.GetName()))
141	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
142	opts = append(c.CallOptions.ListAlertPolicies[0:len(c.CallOptions.ListAlertPolicies):len(c.CallOptions.ListAlertPolicies)], opts...)
143	it := &AlertPolicyIterator{}
144	req = proto.Clone(req).(*monitoringpb.ListAlertPoliciesRequest)
145	it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.AlertPolicy, string, error) {
146		var resp *monitoringpb.ListAlertPoliciesResponse
147		req.PageToken = pageToken
148		if pageSize > math.MaxInt32 {
149			req.PageSize = math.MaxInt32
150		} else {
151			req.PageSize = int32(pageSize)
152		}
153		err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
154			var err error
155			resp, err = c.alertPolicyClient.ListAlertPolicies(ctx, req, settings.GRPC...)
156			return err
157		}, opts...)
158		if err != nil {
159			return nil, "", err
160		}
161		return resp.AlertPolicies, resp.NextPageToken, nil
162	}
163	fetch := func(pageSize int, pageToken string) (string, error) {
164		items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
165		if err != nil {
166			return "", err
167		}
168		it.items = append(it.items, items...)
169		return nextPageToken, nil
170	}
171	it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
172	it.pageInfo.MaxSize = int(req.PageSize)
173	it.pageInfo.Token = req.PageToken
174	return it
175}
176
177// GetAlertPolicy gets a single alerting policy.
178func (c *AlertPolicyClient) GetAlertPolicy(ctx context.Context, req *monitoringpb.GetAlertPolicyRequest, opts ...gax.CallOption) (*monitoringpb.AlertPolicy, error) {
179	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", req.GetName()))
180	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
181	opts = append(c.CallOptions.GetAlertPolicy[0:len(c.CallOptions.GetAlertPolicy):len(c.CallOptions.GetAlertPolicy)], opts...)
182	var resp *monitoringpb.AlertPolicy
183	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
184		var err error
185		resp, err = c.alertPolicyClient.GetAlertPolicy(ctx, req, settings.GRPC...)
186		return err
187	}, opts...)
188	if err != nil {
189		return nil, err
190	}
191	return resp, nil
192}
193
194// CreateAlertPolicy creates a new alerting policy.
195func (c *AlertPolicyClient) CreateAlertPolicy(ctx context.Context, req *monitoringpb.CreateAlertPolicyRequest, opts ...gax.CallOption) (*monitoringpb.AlertPolicy, error) {
196	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", req.GetName()))
197	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
198	opts = append(c.CallOptions.CreateAlertPolicy[0:len(c.CallOptions.CreateAlertPolicy):len(c.CallOptions.CreateAlertPolicy)], opts...)
199	var resp *monitoringpb.AlertPolicy
200	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
201		var err error
202		resp, err = c.alertPolicyClient.CreateAlertPolicy(ctx, req, settings.GRPC...)
203		return err
204	}, opts...)
205	if err != nil {
206		return nil, err
207	}
208	return resp, nil
209}
210
211// DeleteAlertPolicy deletes an alerting policy.
212func (c *AlertPolicyClient) DeleteAlertPolicy(ctx context.Context, req *monitoringpb.DeleteAlertPolicyRequest, opts ...gax.CallOption) error {
213	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", req.GetName()))
214	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
215	opts = append(c.CallOptions.DeleteAlertPolicy[0:len(c.CallOptions.DeleteAlertPolicy):len(c.CallOptions.DeleteAlertPolicy)], opts...)
216	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
217		var err error
218		_, err = c.alertPolicyClient.DeleteAlertPolicy(ctx, req, settings.GRPC...)
219		return err
220	}, opts...)
221	return err
222}
223
224// UpdateAlertPolicy updates an alerting policy. You can either replace the entire policy with
225// a new one or replace only certain fields in the current alerting policy by
226// specifying the fields to be updated via updateMask. Returns the
227// updated alerting policy.
228func (c *AlertPolicyClient) UpdateAlertPolicy(ctx context.Context, req *monitoringpb.UpdateAlertPolicyRequest, opts ...gax.CallOption) (*monitoringpb.AlertPolicy, error) {
229	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "alert_policy.name", req.GetAlertPolicy().GetName()))
230	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
231	opts = append(c.CallOptions.UpdateAlertPolicy[0:len(c.CallOptions.UpdateAlertPolicy):len(c.CallOptions.UpdateAlertPolicy)], opts...)
232	var resp *monitoringpb.AlertPolicy
233	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
234		var err error
235		resp, err = c.alertPolicyClient.UpdateAlertPolicy(ctx, req, settings.GRPC...)
236		return err
237	}, opts...)
238	if err != nil {
239		return nil, err
240	}
241	return resp, nil
242}
243
244// AlertPolicyIterator manages a stream of *monitoringpb.AlertPolicy.
245type AlertPolicyIterator struct {
246	items    []*monitoringpb.AlertPolicy
247	pageInfo *iterator.PageInfo
248	nextFunc func() error
249
250	// InternalFetch is for use by the Google Cloud Libraries only.
251	// It is not part of the stable interface of this package.
252	//
253	// InternalFetch returns results from a single call to the underlying RPC.
254	// The number of results is no greater than pageSize.
255	// If there are no more results, nextPageToken is empty and err is nil.
256	InternalFetch func(pageSize int, pageToken string) (results []*monitoringpb.AlertPolicy, nextPageToken string, err error)
257}
258
259// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
260func (it *AlertPolicyIterator) PageInfo() *iterator.PageInfo {
261	return it.pageInfo
262}
263
264// Next returns the next result. Its second return value is iterator.Done if there are no more
265// results. Once Next returns Done, all subsequent calls will return Done.
266func (it *AlertPolicyIterator) Next() (*monitoringpb.AlertPolicy, error) {
267	var item *monitoringpb.AlertPolicy
268	if err := it.nextFunc(); err != nil {
269		return item, err
270	}
271	item = it.items[0]
272	it.items = it.items[1:]
273	return item, nil
274}
275
276func (it *AlertPolicyIterator) bufLen() int {
277	return len(it.items)
278}
279
280func (it *AlertPolicyIterator) takeBuf() interface{} {
281	b := it.items
282	it.items = nil
283	return b
284}
285