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