feat: Add new gcloud commands, API clients, and third-party libraries across various services.

This commit is contained in:
2026-01-01 20:26:35 +01:00
parent 5e23cbece0
commit a19e592eb7
25221 changed files with 8324611 additions and 0 deletions

View File

@@ -0,0 +1,47 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""API utilities for `gcloud network-security` commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.core import resources
API_VERSION_FOR_TRACK = {
base.ReleaseTrack.ALPHA: 'v1alpha1',
base.ReleaseTrack.BETA: 'v1beta1',
base.ReleaseTrack.GA: 'v1',
}
API_NAME = 'networksecurity'
def GetMessagesModule(release_track=base.ReleaseTrack.BETA):
api_version = API_VERSION_FOR_TRACK.get(release_track)
return apis.GetMessagesModule(API_NAME, api_version)
def GetClientInstance(release_track=base.ReleaseTrack.BETA):
api_version = API_VERSION_FOR_TRACK.get(release_track)
return apis.GetClientInstance(API_NAME, api_version)
def GetApiBaseUrl(release_track=base.ReleaseTrack.ALPHA):
api_version = API_VERSION_FOR_TRACK.get(release_track)
return resources.GetApiBaseUrlOrDefault(
API_NAME, api_version, 'https://networksecurity.googleapis.com/'
)

View File

@@ -0,0 +1,175 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""API wrapper for `gcloud network-security firewall-attachment` commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import datetime
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.api_lib.util import waiter
from googlecloudsdk.calliope import base
from googlecloudsdk.core import resources
_API_VERSION_FOR_TRACK = {
base.ReleaseTrack.ALPHA: 'v1alpha1',
base.ReleaseTrack.BETA: 'v1beta1',
base.ReleaseTrack.GA: 'v1',
}
_API_NAME = 'networksecurity'
def GetMessagesModule(release_track=base.ReleaseTrack.ALPHA):
api_version = _API_VERSION_FOR_TRACK.get(release_track)
return apis.GetMessagesModule(_API_NAME, api_version)
def GetClientInstance(release_track=base.ReleaseTrack.ALPHA):
api_version = _API_VERSION_FOR_TRACK.get(release_track)
return apis.GetClientInstance(_API_NAME, api_version)
def GetEffectiveApiEndpoint(release_track=base.ReleaseTrack.ALPHA):
api_version = _API_VERSION_FOR_TRACK.get(release_track)
return apis.GetEffectiveApiEndpoint(_API_NAME, api_version)
def GetApiBaseUrl(release_track=base.ReleaseTrack.ALPHA):
api_version = _API_VERSION_FOR_TRACK.get(release_track)
return resources.GetApiBaseUrlOrThrow(_API_NAME, api_version)
def GetApiVersion(release_track=base.ReleaseTrack.ALPHA):
return _API_VERSION_FOR_TRACK.get(release_track)
class Client:
"""API client for Firewall Attachment commands.
Attributes:
messages: API messages class, The Firewall Plus API messages.
"""
def __init__(self, release_track):
self._client = GetClientInstance(release_track)
self._attachment_client = (
self._client.projects_locations_firewallAttachments
)
self._operations_client = self._client.projects_locations_operations
self.messages = GetMessagesModule(release_track)
self._resource_parser = resources.Registry()
self._resource_parser.RegisterApiByName(
'networksecurity', _API_VERSION_FOR_TRACK.get(release_track)
)
def CreateAttachment(
self,
attachment_id,
parent,
producer_forwarding_rule_name,
labels=None,
):
"""Calls the CreateAttachment API."""
attachment = self.messages.FirewallAttachment(
producerForwardingRuleName=producer_forwarding_rule_name,
labels=labels,
)
create_request = self.messages.NetworksecurityProjectsLocationsFirewallAttachmentsCreateRequest(
firewallAttachment=attachment,
firewallAttachmentId=attachment_id,
parent=parent,
)
return self._attachment_client.Create(create_request)
def DeleteAttachment(self, name):
"""Calls the DeleteAttachment API."""
delete_request = self.messages.NetworksecurityProjectsLocationsFirewallAttachmentsDeleteRequest(
name=name
)
return self._attachment_client.Delete(delete_request)
def DescribeAttachment(self, name):
"""Calls the GetAttachment API."""
get_request = self.messages.NetworksecurityProjectsLocationsFirewallAttachmentsGetRequest(
name=name
)
return self._attachment_client.Get(get_request)
def ListAttachments(
self, parent, limit=None, page_size=None
):
"""Calls the ListAttachments API."""
list_request = self.messages.NetworksecurityProjectsLocationsFirewallAttachmentsListRequest(
parent=parent
)
return list_pager.YieldFromList(
self._attachment_client,
list_request,
batch_size=page_size,
limit=limit,
field='firewallAttachments',
batch_size_attribute='pageSize',
)
def GetOperationRef(self, operation):
"""Converts an Operation to a Resource to use with `waiter.WaitFor`."""
return self._resource_parser.ParseRelativeName(
operation.name, 'networksecurity.projects.locations.operations'
)
def WaitForOperation(
self,
operation_ref,
message,
has_result=True,
max_wait=datetime.timedelta(seconds=600),
):
"""Waits for an operation to complete.
Polls the Firewall Attachment Operation service until the operation
completes, fails, or max_wait_seconds elapses.
Args:
operation_ref: A Resource created by GetOperationRef describing the
Operation.
message: The message to display to the user while they wait.
has_result: If True, the function will return the target of the operation
(the Firewall Attachment) when it completes. If False, nothing will
be returned (useful for Delete operations)
max_wait: The time to wait for the operation to succeed before timing out.
Returns:
If has_result = True, an Attachment entity.
Otherwise, None.
"""
if has_result:
poller = waiter.CloudOperationPoller(
self._attachment_client, self._operations_client
)
else:
poller = waiter.CloudOperationPollerNoResources(self._operations_client)
return waiter.WaitFor(
poller,
operation_ref,
message,
max_wait_ms=int(max_wait.total_seconds()) * 1000,
)

View File

@@ -0,0 +1,223 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""API wrapper for `gcloud network-security firewall-endpoint-associations` commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import datetime
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.api_lib.util import waiter
from googlecloudsdk.calliope import base
from googlecloudsdk.core import resources
_API_VERSION_FOR_TRACK = {
base.ReleaseTrack.ALPHA: 'v1alpha1',
base.ReleaseTrack.BETA: 'v1beta1',
base.ReleaseTrack.GA: 'v1',
}
_API_NAME = 'networksecurity'
def GetMessagesModule(release_track=base.ReleaseTrack.GA):
api_version = _API_VERSION_FOR_TRACK.get(release_track)
return apis.GetMessagesModule(_API_NAME, api_version)
def GetClientInstance(release_track=base.ReleaseTrack.GA):
api_version = _API_VERSION_FOR_TRACK.get(release_track)
return apis.GetClientInstance(_API_NAME, api_version)
def GetEffectiveApiEndpoint(release_track=base.ReleaseTrack.GA):
api_version = _API_VERSION_FOR_TRACK.get(release_track)
return apis.GetEffectiveApiEndpoint(_API_NAME, api_version)
def GetApiBaseUrl(release_track=base.ReleaseTrack.GA):
api_version = _API_VERSION_FOR_TRACK.get(release_track)
return resources.GetApiBaseUrlOrThrow(_API_NAME, api_version)
class Client:
"""API client for FWP association commands.
Attributes:
messages: API messages class, The Firewall Plus API messages.
"""
def __init__(self, release_track):
self._client = GetClientInstance(release_track)
self._association_client = (
self._client.projects_locations_firewallEndpointAssociations
)
self._operations_client = self._client.projects_locations_operations
self.messages = GetMessagesModule(release_track)
self._resource_parser = resources.Registry()
self._resource_parser.RegisterApiByName(
'networksecurity', _API_VERSION_FOR_TRACK.get(release_track)
)
def CreateAssociation(
self,
parent,
network,
firewall_endpoint,
association_id=None,
tls_inspection_policy=None,
labels=None,
):
"""Calls the CreateAssociation API.
Args:
parent: The parent of the association, e.g.
"projects/myproj/locations/us-central1-a"
network: The network of the association, e.g.
"projects/myproj/networks/global/my-vpc"
firewall_endpoint: The firewall endpoint of the association, e.g. "
organizations/123456/locations/us-central1-a/firewallEndpoints/my-ep"
association_id: The ID of the association, e.g. "my-assoc".
tls_inspection_policy: The TLS inspection policy of the association, e.g.
"projects/my-proj/locations/us-central1/tlsInspectionPolicies/my-tls".
labels: A dictionary with the labels of the association.
Returns:
NetworksecurityProjectsLocationsFirewallEndpointAssociationsCreateResponse
"""
association = self.messages.FirewallEndpointAssociation(
network=network,
firewallEndpoint=firewall_endpoint,
labels=labels,
tlsInspectionPolicy=tls_inspection_policy,
)
create_request = self.messages.NetworksecurityProjectsLocationsFirewallEndpointAssociationsCreateRequest(
firewallEndpointAssociation=association,
firewallEndpointAssociationId=association_id,
parent=parent,
)
return self._association_client.Create(create_request)
def UpdateAssociation(
self,
name,
update_fields,
):
"""Calls the UpdateAssociation API to modify an existing association.
Args:
name: The resource name of the association.
update_fields: A dictionary mapping from field names to update, to their
new values. Supported values: 'labels', 'tls_inspection_policy',
'disabled'.
Returns:
NetworksecurityProjectsLocationsFirewallEndpointAssociationsPatchResponse
"""
# Only keys that exist in the dictionary are updated. This is done via the
# updateMask request parameter. Values for keys that do not exist in the
# dictionary can be anything and will not be updated.
association = self.messages.FirewallEndpointAssociation(
disabled=update_fields.get('disabled', None),
labels=update_fields.get('labels', None),
tlsInspectionPolicy=update_fields.get('tls_inspection_policy', None),
)
update_request = self.messages.NetworksecurityProjectsLocationsFirewallEndpointAssociationsPatchRequest(
name=name,
firewallEndpointAssociation=association,
updateMask=','.join(update_fields.keys()),
)
return self._association_client.Patch(update_request)
def DeleteAssociation(self, name):
"""Calls the DeleteAssociation API."""
delete_request = self.messages.NetworksecurityProjectsLocationsFirewallEndpointAssociationsDeleteRequest(
name=name
)
return self._association_client.Delete(delete_request)
def DescribeAssociation(self, name):
"""Calls the GetAssociation API."""
get_request = self.messages.NetworksecurityProjectsLocationsFirewallEndpointAssociationsGetRequest(
name=name
)
return self._association_client.Get(get_request)
def ListAssociations(
self, parent, limit=None, page_size=None, list_filter=None
):
"""Calls the ListAssociations API."""
list_request = self.messages.NetworksecurityProjectsLocationsFirewallEndpointAssociationsListRequest(
parent=parent, filter=list_filter
)
return list_pager.YieldFromList(
self._association_client,
list_request,
batch_size=page_size,
limit=limit,
field='firewallEndpointAssociations',
batch_size_attribute='pageSize',
)
def GetOperationRef(self, operation):
"""Converts an Operation to a Resource to use with `waiter.WaitFor`."""
return self._resource_parser.ParseRelativeName(
operation.name, 'networksecurity.projects.locations.operations'
)
def WaitForOperation(
self,
operation_ref,
message,
has_result=True,
max_wait=datetime.timedelta(seconds=600),
):
"""Waits for an operation to complete.
Polls the Firewall Plus Operation service until the operation completes,
fails, or max_wait_seconds elapses.
Args:
operation_ref: A Resource created by GetOperationRef describing the
Operation.
message: The message to display to the user while they wait.
has_result: If True, the function will return the target of the operation
(the Firewall Plus Endpoint) when it completes. If False, nothing will
be returned (useful for Delete operations)
max_wait: The time to wait for the operation to succeed before timing out.
Returns:
If has_result = True, an Endpoint entity.
Otherwise, None.
"""
if has_result:
poller = waiter.CloudOperationPoller(
self._association_client, self._operations_client
)
else:
poller = waiter.CloudOperationPollerNoResources(self._operations_client)
return waiter.WaitFor(
poller,
operation_ref,
message,
max_wait_ms=int(max_wait.total_seconds()) * 1000,
)

View File

@@ -0,0 +1,236 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""API wrapper for `gcloud network-security firewall-endpoints` commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import datetime
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.api_lib.util import waiter
from googlecloudsdk.calliope import base
from googlecloudsdk.core import resources
_API_VERSION_FOR_TRACK = {
base.ReleaseTrack.ALPHA: 'v1alpha1',
base.ReleaseTrack.BETA: 'v1beta1',
base.ReleaseTrack.GA: 'v1',
}
_API_NAME = 'networksecurity'
def GetMessagesModule(release_track=base.ReleaseTrack.GA):
api_version = _API_VERSION_FOR_TRACK.get(release_track)
return apis.GetMessagesModule(_API_NAME, api_version)
def GetClientInstance(release_track=base.ReleaseTrack.GA):
api_version = _API_VERSION_FOR_TRACK.get(release_track)
return apis.GetClientInstance(_API_NAME, api_version)
def GetEffectiveApiEndpoint(release_track=base.ReleaseTrack.GA):
api_version = _API_VERSION_FOR_TRACK.get(release_track)
return apis.GetEffectiveApiEndpoint(_API_NAME, api_version)
def GetApiBaseUrl(release_track=base.ReleaseTrack.GA):
api_version = _API_VERSION_FOR_TRACK.get(release_track)
return resources.GetApiBaseUrlOrThrow(_API_NAME, api_version)
def GetApiVersion(release_track=base.ReleaseTrack.GA):
return _API_VERSION_FOR_TRACK.get(release_track)
class Client:
"""API client for FWP activation commands.
Attributes:
messages: API messages class, The Firewall Plus API messages.
"""
def __init__(self, release_track):
self._client = GetClientInstance(release_track)
self._endpoint_client = (
self._client.organizations_locations_firewallEndpoints
)
self._operations_client = self._client.organizations_locations_operations
self.messages = GetMessagesModule(release_track)
self._resource_parser = resources.Registry()
self._resource_parser.RegisterApiByName(
'networksecurity', _API_VERSION_FOR_TRACK.get(release_track)
)
def _ParseEndpointType(self, endpoint_type):
if endpoint_type is None:
return None
return self.messages.FirewallEndpoint.TypeValueValuesEnum.lookup_by_name(
endpoint_type
)
def _ParseThirdPartyEndpointSettings(self, target_firewall_attachment):
if target_firewall_attachment is None:
return None
return self.messages.ThirdPartyEndpointSettings(
targetFirewallAttachment=target_firewall_attachment,
)
def _ParseEndpointSettings(self, enable_jumbo_frames):
return self.messages.FirewallEndpointEndpointSettings(
jumboFramesEnabled=enable_jumbo_frames,
)
def CreateEndpoint(
self,
name,
parent,
description,
billing_project_id,
enable_jumbo_frames,
endpoint_type=None,
target_firewall_attachment=None,
labels=None,
):
"""Calls the CreateEndpoint API."""
third_party_endpoint_settings = self._ParseThirdPartyEndpointSettings(
target_firewall_attachment
)
if endpoint_type is not None:
endpoint = self.messages.FirewallEndpoint(
labels=labels,
type=self._ParseEndpointType(endpoint_type),
thirdPartyEndpointSettings=third_party_endpoint_settings,
description=description,
billingProjectId=billing_project_id,
)
else:
endpoint = self.messages.FirewallEndpoint(
labels=labels,
description=description,
billingProjectId=billing_project_id,
)
if enable_jumbo_frames is not None:
endpoint.endpointSettings = self._ParseEndpointSettings(
enable_jumbo_frames
)
create_request = self.messages.NetworksecurityOrganizationsLocationsFirewallEndpointsCreateRequest(
firewallEndpoint=endpoint, firewallEndpointId=name, parent=parent
)
return self._endpoint_client.Create(create_request)
def UpdateEndpoint(
self, name, description, update_mask, labels=None, billing_project_id=None
):
"""Calls the UpdateEndpoint API.
Args:
name: str, full name of the firewall endpoint.
description: str, description of the firewall endpoint.
update_mask: str, comma separated list of fields to update.
labels: LabelsValue, labels for the firewall endpoint.
billing_project_id: str, billing project ID.
Returns:
Operation ref to track the long-running process.
"""
endpoint = self.messages.FirewallEndpoint(
labels=labels,
description=description,
billingProjectId=billing_project_id,
)
update_request = self.messages.NetworksecurityOrganizationsLocationsFirewallEndpointsPatchRequest(
name=name,
firewallEndpoint=endpoint,
updateMask=update_mask,
)
return self._endpoint_client.Patch(update_request)
def DeleteEndpoint(self, name):
"""Calls the DeleteEndpoint API."""
delete_request = self.messages.NetworksecurityOrganizationsLocationsFirewallEndpointsDeleteRequest(
name=name
)
return self._endpoint_client.Delete(delete_request)
def DescribeEndpoint(self, name):
"""Calls the GetEndpoint API."""
get_request = self.messages.NetworksecurityOrganizationsLocationsFirewallEndpointsGetRequest(
name=name
)
return self._endpoint_client.Get(get_request)
def ListEndpoints(self, parent, limit=None, page_size=None, list_filter=None):
"""Calls the ListEndpoints API."""
list_request = self.messages.NetworksecurityOrganizationsLocationsFirewallEndpointsListRequest(
parent=parent, filter=list_filter
)
return list_pager.YieldFromList(
self._endpoint_client,
list_request,
batch_size=page_size,
limit=limit,
field='firewallEndpoints',
batch_size_attribute='pageSize',
)
def GetOperationRef(self, operation):
"""Converts an Operation to a Resource that can be used with `waiter.WaitFor`."""
return self._resource_parser.ParseRelativeName(
operation.name, 'networksecurity.organizations.locations.operations'
)
def WaitForOperation(
self,
operation_ref,
message,
has_result=True,
max_wait=datetime.timedelta(seconds=600),
):
"""Waits for an operation to complete.
Polls the Firewall Plus Operation service until the operation completes,
fails, or max_wait_seconds elapses.
Args:
operation_ref: A Resource created by GetOperationRef describing the
Operation.
message: The message to display to the user while they wait.
has_result: If True, the function will return the target of the operation
(the Firewall Plus Endpoint) when it completes. If False, nothing will
be returned (useful for Delete operations)
max_wait: The time to wait for the operation to succeed before timing out.
Returns:
if has_result = True, an Endpoint entity.
Otherwise, None.
"""
if has_result:
poller = waiter.CloudOperationPoller(
self._endpoint_client, self._operations_client
)
else:
poller = waiter.CloudOperationPollerNoResources(self._operations_client)
return waiter.WaitFor(
poller,
operation_ref,
message,
max_wait_ms=int(max_wait.total_seconds()) * 1000,
)

View File

@@ -0,0 +1,14 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

View File

@@ -0,0 +1,247 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""API wrapper for `gcloud network-security intercept-deployment-groups` commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import datetime
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.api_lib.util import waiter
from googlecloudsdk.calliope import base
from googlecloudsdk.core import resources
_API_VERSION_FOR_TRACK = {
base.ReleaseTrack.ALPHA: 'v1alpha1',
base.ReleaseTrack.BETA: 'v1beta1',
base.ReleaseTrack.GA: 'v1',
}
_API_NAME = 'networksecurity'
def GetMessagesModule(release_track=base.ReleaseTrack.BETA):
api_version = GetApiVersion(release_track)
return apis.GetMessagesModule(_API_NAME, api_version)
def GetClientInstance(release_track=base.ReleaseTrack.BETA):
api_version = GetApiVersion(release_track)
return apis.GetClientInstance(_API_NAME, api_version)
def GetEffectiveApiEndpoint(release_track=base.ReleaseTrack.BETA):
api_version = GetApiVersion(release_track)
return apis.GetEffectiveApiEndpoint(_API_NAME, api_version)
def GetApiVersion(release_track=base.ReleaseTrack.BETA):
return _API_VERSION_FOR_TRACK.get(release_track)
class Client:
"""API client for Intercept Deployment Groups commands.
Attributes:
messages: API messages class, The Intercept Deployment Groups messages.
"""
def __init__(self, release_track):
self._client = GetClientInstance(release_track)
self._deployment_group_client = (
self._client.projects_locations_interceptDeploymentGroups
)
self._operations_client = self._client.projects_locations_operations
self.messages = GetMessagesModule(release_track)
self._resource_parser = resources.Registry()
self._resource_parser.RegisterApiByName(
_API_NAME, GetApiVersion(release_track)
)
def CreateDeploymentGroup(
self,
deployment_group_id: str,
parent: str,
network: str,
description: str,
labels=None,
):
"""Calls the CreateDeploymentGroup API.
Args:
deployment_group_id: str, the id of the intercept deployment group.
parent: str, the parent resource name.
network: str, the network used for all group deployments.
description: str, The description of the Endpoint Group.
labels: LabelsValue, optional labels as key-value pairs.
Returns:
Operation ref to track the long-running process.
"""
deployment_group = self.messages.InterceptDeploymentGroup(
labels=labels,
network=network,
)
# TODO(b/391304673): Remove this check once the field is
# available in V1.
if hasattr(deployment_group, 'description'):
deployment_group.description = description
create_request = self.messages.NetworksecurityProjectsLocationsInterceptDeploymentGroupsCreateRequest(
interceptDeploymentGroup=deployment_group,
interceptDeploymentGroupId=deployment_group_id,
parent=parent,
)
return self._deployment_group_client.Create(create_request)
def DeleteDeploymentGroup(self, name):
"""Calls the DeleteDeploymentGroup API.
Args:
name: str, the name of the intercept deployment group.
Returns:
Operation ref to track the long-running process.
"""
delete_request = self.messages.NetworksecurityProjectsLocationsInterceptDeploymentGroupsDeleteRequest(
name=name
)
return self._deployment_group_client.Delete(delete_request)
def UpdateDeploymentGroup(
self,
name,
description,
update_fields,
):
"""Calls the UpdateDeploymentGroup API.
Args:
name: str, the name of the intercept deployment group.
description: str, the description of the intercept deployment group.
update_fields: A dictionary of fields to update mapped to their new
values.
Returns:
Operation ref to track the long-running process.
"""
dg = self.messages.InterceptDeploymentGroup(
labels=update_fields.get('labels', None),
)
# TODO(b/391304673): Remove this check once the field is
# available in V1.
if hasattr(dg, 'description'):
dg.description = description
update_request = self.messages.NetworksecurityProjectsLocationsInterceptDeploymentGroupsPatchRequest(
name=name,
interceptDeploymentGroup=dg,
updateMask=','.join(update_fields.keys()),
)
return self._deployment_group_client.Patch(update_request)
def DescribeDeploymentGroup(self, name):
"""Calls the GetDeploymentGroup API.
Args:
name: str, the name of the intercept deployment group.
Returns:
The intercept deployment group object.
"""
get_request = self.messages.NetworksecurityProjectsLocationsInterceptDeploymentGroupsGetRequest(
name=name
)
return self._deployment_group_client.Get(get_request)
def ListDeploymentGroups(
self, parent, limit=None, page_size=None, list_filter=None
):
"""Calls the ListDeploymentGroups API.
Args:
parent: str, the parent resource name.
limit: int, optional limit for the number of results.
page_size: int, optional page size for the results.
list_filter: str, optional filter for the results.
Returns:
A generator yielding intercept deployment groups.
"""
list_request = self.messages.NetworksecurityProjectsLocationsInterceptDeploymentGroupsListRequest(
parent=parent, filter=list_filter
)
return list_pager.YieldFromList(
self._deployment_group_client,
list_request,
batch_size=page_size,
limit=limit,
field='interceptDeploymentGroups',
batch_size_attribute='pageSize',
)
def GetOperationRef(self, operation):
"""Converts an Operation to a Resource that can be used with `waiter.WaitFor`.
Args:
operation: The operation object.
Returns:
A Resource describing the operation.
"""
return self._resource_parser.ParseRelativeName(
operation.name, 'networksecurity.projects.locations.operations'
)
def WaitForOperation(
self,
operation_ref,
message,
has_result=True,
max_wait=datetime.timedelta(seconds=600),
):
"""Waits for an operation to complete.
Polls the Firewall Plus Operation service until the operation completes,
fails, or max_wait_seconds elapses.
Args:
operation_ref: A Resource created by GetOperationRef describing the
operation.
message: str, the message to display to the user while they wait.
has_result: bool, if True, returns the target of the operation when it
completes.
max_wait: datetime.timedelta, the maximum time to wait for the operation
to succeed.
Returns:
if has_result = True, a InterceptDeploymentGroup entity. Otherwise, None.
"""
if has_result:
poller = waiter.CloudOperationPoller(
self._deployment_group_client, self._operations_client
)
else:
poller = waiter.CloudOperationPollerNoResources(self._operations_client)
return waiter.WaitFor(
poller,
operation_ref,
message,
max_wait_ms=int(max_wait.total_seconds()) * 1000,
)

View File

@@ -0,0 +1,14 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

View File

@@ -0,0 +1,224 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""API wrapper for `gcloud network-security intercept-deployments` commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import datetime
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.api_lib.util import waiter
from googlecloudsdk.calliope import base
from googlecloudsdk.core import resources
_API_VERSION_FOR_TRACK = {
base.ReleaseTrack.ALPHA: 'v1alpha1',
base.ReleaseTrack.BETA: 'v1beta1',
base.ReleaseTrack.GA: 'v1',
}
_API_NAME = 'networksecurity'
def GetMessagesModule(release_track=base.ReleaseTrack.BETA):
api_version = GetApiVersion(release_track)
return apis.GetMessagesModule(_API_NAME, api_version)
def GetClientInstance(release_track=base.ReleaseTrack.BETA):
api_version = GetApiVersion(release_track)
return apis.GetClientInstance(_API_NAME, api_version)
def GetEffectiveApiEndpoint(release_track=base.ReleaseTrack.BETA):
api_version = GetApiVersion(release_track)
return apis.GetEffectiveApiEndpoint(_API_NAME, api_version)
def GetApiVersion(release_track=base.ReleaseTrack.BETA):
return _API_VERSION_FOR_TRACK.get(release_track)
class Client:
"""API client for Intercept Deployments commands.
Attributes:
messages: API messages class, The Network Security API messages.
"""
def __init__(self, release_track):
self._client = GetClientInstance(release_track)
self._deployments_client = (
self._client.projects_locations_interceptDeployments
)
self._operations_client = self._client.projects_locations_operations
self.messages = GetMessagesModule(release_track)
self._resource_parser = resources.Registry()
self._resource_parser.RegisterApiByName(
_API_NAME, GetApiVersion(release_track)
)
def CreateDeployment(
self,
parent,
forwarding_rule,
intercept_deployment_group,
description,
deployment_id=None,
labels=None,
):
"""Calls the CreateInterceptDeployment API.
Args:
parent: The parent of the deployment, e.g.
"projects/myproj/locations/us-central1"
forwarding_rule: The forwarding rule of the deployment, e.g.
"projects/myproj/regions/us-central1/forwardingRules/my-rule"
intercept_deployment_group: The deployment group of the deployment, e.g.
"projects/myproj/locations/global/interceptDeploymentGroups/my-group"
description: The description of the deployment.
deployment_id: The ID of the deployment, e.g. "my-deployment".
labels: A dictionary with the labels of the deployment.
Returns:
NetworksecurityProjectsLocationsInterceptDeploymentsCreateResponse
"""
deployment = self.messages.InterceptDeployment(
forwardingRule=forwarding_rule,
interceptDeploymentGroup=intercept_deployment_group,
labels=labels,
)
# TODO(b/391304673): Remove this check once the field is
# available in V1.
if hasattr(deployment, 'description'):
deployment.description = description
create_request = self.messages.NetworksecurityProjectsLocationsInterceptDeploymentsCreateRequest(
interceptDeployment=deployment,
interceptDeploymentId=deployment_id,
parent=parent,
)
return self._deployments_client.Create(create_request)
def DeleteDeployment(self, name):
"""Calls the DeleteInterceptDeployment API."""
delete_request = self.messages.NetworksecurityProjectsLocationsInterceptDeploymentsDeleteRequest(
name=name
)
return self._deployments_client.Delete(delete_request)
def UpdateDeployment(
self,
name,
description,
update_fields,
):
"""Calls the UpdateInterceptDeployment API.
Args:
name: The name of the deployment.
description: The description of the deployment.
update_fields: A dictionary of the fields to update mapped to their new
values.
Returns:
Operation ref to track the long-running process.
"""
deployment = self.messages.InterceptDeployment(
labels=update_fields.get('labels', None),
)
# TODO(b/391304673): Remove this check once the field is
# available in V1.
if hasattr(deployment, 'description'):
deployment.description = description
update_request = self.messages.NetworksecurityProjectsLocationsInterceptDeploymentsPatchRequest(
name=name,
interceptDeployment=deployment,
updateMask=','.join(update_fields.keys())
)
return self._deployments_client.Patch(update_request)
def DescribeDeployment(self, name):
"""Calls the GetInterceptDeployment API."""
get_request = self.messages.NetworksecurityProjectsLocationsInterceptDeploymentsGetRequest(
name=name
)
return self._deployments_client.Get(get_request)
def ListDeployments(
self, parent, limit=None, page_size=None, list_filter=None
):
"""Calls the ListInterceptDeployments API."""
list_request = self.messages.NetworksecurityProjectsLocationsInterceptDeploymentsListRequest(
parent=parent, filter=list_filter
)
return list_pager.YieldFromList(
self._deployments_client,
list_request,
batch_size=page_size,
limit=limit,
field='interceptDeployments',
batch_size_attribute='pageSize',
)
def GetOperationRef(self, operation):
"""Converts an Operation to a Resource to use with `waiter.WaitFor`."""
return self._resource_parser.ParseRelativeName(
operation.name, 'networksecurity.projects.locations.operations'
)
def WaitForOperation(
self,
operation_ref,
message,
has_result=True,
max_wait=datetime.timedelta(seconds=600),
):
"""Waits for an operation to complete.
Polls the Network Security Operation service until the operation completes,
fails, or max_wait_seconds elapses.
Args:
operation_ref: A Resource created by GetOperationRef describing the
Operation.
message: The message to display to the user while they wait.
has_result: If True, the function will return the target of the operation
(the Intercept Deployment) when it completes. If False, nothing will be
returned (useful for Delete operations).
max_wait: The time to wait for the operation to succeed before timing out.
Returns:
If has_result = True, an Intercept Deployment entity.
Otherwise, None.
"""
if has_result:
poller = waiter.CloudOperationPoller(
self._deployments_client, self._operations_client
)
else:
poller = waiter.CloudOperationPollerNoResources(self._operations_client)
return waiter.WaitFor(
poller,
operation_ref,
message,
max_wait_ms=int(max_wait.total_seconds()) * 1000,
)

View File

@@ -0,0 +1,14 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

View File

@@ -0,0 +1,189 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""API wrapper for `gcloud network-security intercept-endpoint-group-associations` commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import datetime
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.api_lib.util import waiter
from googlecloudsdk.calliope import base
from googlecloudsdk.core import resources
_API_VERSION_FOR_TRACK = {
base.ReleaseTrack.ALPHA: 'v1alpha1',
base.ReleaseTrack.BETA: 'v1beta1',
base.ReleaseTrack.GA: 'v1',
}
_API_NAME = 'networksecurity'
def GetMessagesModule(release_track=base.ReleaseTrack.BETA):
api_version = GetApiVersion(release_track)
return apis.GetMessagesModule(_API_NAME, api_version)
def GetClientInstance(release_track=base.ReleaseTrack.BETA):
api_version = GetApiVersion(release_track)
return apis.GetClientInstance(_API_NAME, api_version)
def GetEffectiveApiEndpoint(release_track=base.ReleaseTrack.BETA):
api_version = GetApiVersion(release_track)
return apis.GetEffectiveApiEndpoint(_API_NAME, api_version)
def GetApiVersion(release_track=base.ReleaseTrack.BETA):
return _API_VERSION_FOR_TRACK.get(release_track)
class Client:
"""API client for Intercept Endpoint Group Association commands.
Attributes:
messages: API messages class, The Intercept Endpoint Group Association API
messages.
"""
def __init__(self, release_track):
self._client = GetClientInstance(release_track)
self._association_client = (
self._client.projects_locations_interceptEndpointGroupAssociations
)
self._operations_client = self._client.projects_locations_operations
self.messages = GetMessagesModule(release_track)
self._resource_parser = resources.Registry()
self._resource_parser.RegisterApiByName(
_API_NAME, GetApiVersion(release_track)
)
def CreateEndpointGroupAssociation(
self,
association_id,
parent,
network,
intercept_endpoint_group,
labels=None,
):
"""Calls the CreateEndpointGroupAssociation API."""
association = self.messages.InterceptEndpointGroupAssociation(
labels=labels,
network=network,
interceptEndpointGroup=intercept_endpoint_group,
)
create_request = self.messages.NetworksecurityProjectsLocationsInterceptEndpointGroupAssociationsCreateRequest(
interceptEndpointGroupAssociation=association,
interceptEndpointGroupAssociationId=association_id,
parent=parent,
)
return self._association_client.Create(create_request)
def DeleteEndpointGroupAssociation(self, name):
"""Calls the DeleteEndpointGroupAssociation API."""
delete_request = self.messages.NetworksecurityProjectsLocationsInterceptEndpointGroupAssociationsDeleteRequest(
name=name
)
return self._association_client.Delete(delete_request)
def UpdateEndpointGroupAssociation(
self,
name,
update_fields,
):
"""Calls the UpdateEndpointGroupAssociation API."""
association = self.messages.InterceptEndpointGroupAssociation(
labels=update_fields.get('labels', None)
)
update_request = self.messages.NetworksecurityProjectsLocationsInterceptEndpointGroupAssociationsPatchRequest(
name=name,
interceptEndpointGroupAssociation=association,
updateMask=','.join(update_fields.keys()),
)
return self._association_client.Patch(update_request)
def DescribeEndpointGroupAssociation(self, name):
"""Calls the GetEndpointGroupAssociation API."""
get_request = self.messages.NetworksecurityProjectsLocationsInterceptEndpointGroupAssociationsGetRequest(
name=name
)
return self._association_client.Get(get_request)
def ListEndpointGroupAssociations(
self, parent, limit=None, page_size=None, list_filter=None
):
"""Calls the ListEndpointGroupAssociations API."""
list_request = self.messages.NetworksecurityProjectsLocationsInterceptEndpointGroupAssociationsListRequest(
parent=parent, filter=list_filter
)
return list_pager.YieldFromList(
self._association_client,
list_request,
batch_size=page_size,
limit=limit,
field='interceptEndpointGroupAssociations',
batch_size_attribute='pageSize',
)
def GetOperationRef(self, operation):
"""Converts an Operation to a Resource that can be used with `waiter.WaitFor`."""
return self._resource_parser.ParseRelativeName(
operation.name, 'networksecurity.projects.locations.operations'
)
def WaitForOperation(
self,
operation_ref,
message,
has_result=True,
max_wait=datetime.timedelta(seconds=600),
):
"""Waits for an operation to complete.
Polls the Intercept Endpoint Group Association Operation service until the
operation completes,
fails, or max_wait_seconds elapses.
Args:
operation_ref: A Resource created by GetOperationRef describing the
Operation.
message: The message to display to the user while they wait.
has_result: If True, the function will return the target of the operation
(the Intercept Endpoint Group Association) when it completes. If False,
nothing will be returned (useful for Delete operations)
max_wait: The time to wait for the operation to succeed before timing out.
Returns:
if has_result = True, an Association entity.
Otherwise, None.
"""
if has_result:
poller = waiter.CloudOperationPoller(
self._association_client, self._operations_client
)
else:
poller = waiter.CloudOperationPollerNoResources(self._operations_client)
return waiter.WaitFor(
poller,
operation_ref,
message,
max_wait_ms=int(max_wait.total_seconds()) * 1000,
)

View File

@@ -0,0 +1,14 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

View File

@@ -0,0 +1,221 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""API wrapper for `gcloud network-security intercept-endpoint-groups` commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import datetime
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.api_lib.util import waiter
from googlecloudsdk.calliope import base
from googlecloudsdk.core import resources
_API_VERSION_FOR_TRACK = {
base.ReleaseTrack.ALPHA: 'v1alpha1',
base.ReleaseTrack.BETA: 'v1beta1',
base.ReleaseTrack.GA: 'v1',
}
_API_NAME = 'networksecurity'
def GetMessagesModule(release_track=base.ReleaseTrack.BETA):
api_version = GetApiVersion(release_track)
return apis.GetMessagesModule(_API_NAME, api_version)
def GetClientInstance(release_track=base.ReleaseTrack.BETA):
api_version = GetApiVersion(release_track)
return apis.GetClientInstance(_API_NAME, api_version)
def GetEffectiveApiEndpoint(release_track=base.ReleaseTrack.BETA):
api_version = GetApiVersion(release_track)
return apis.GetEffectiveApiEndpoint(_API_NAME, api_version)
def GetApiVersion(release_track=base.ReleaseTrack.BETA):
return _API_VERSION_FOR_TRACK.get(release_track)
class Client:
"""API client for Intercept Endpoint Groups commands.
Attributes:
messages: API messages class, The Intercept Endpoint Groups API messages.
"""
def __init__(self, release_track):
self._client = GetClientInstance(release_track)
self._endpoint_group_client = (
self._client.projects_locations_interceptEndpointGroups
)
self._operations_client = self._client.projects_locations_operations
self.messages = GetMessagesModule(release_track)
self._resource_parser = resources.Registry()
self._resource_parser.RegisterApiByName(
_API_NAME, GetApiVersion(release_track)
)
def CreateEndpointGroup(
self,
endpoint_group_id,
parent,
intercept_deployment_group,
description,
labels=None,
):
"""Calls the CreateEndpointGroup API.
Args:
endpoint_group_id: The ID of the Endpoint Group to create.
parent: The parent of the Endpoint Group to create.
intercept_deployment_group: The Intercept Deployment Group to associate
with the Endpoint Group.
description: The description of the Endpoint Group.
labels: Labels to apply to the Endpoint Group.
Returns:
Operation ref to track the long-running process.
"""
endpoint_group = self.messages.InterceptEndpointGroup(
labels=labels,
interceptDeploymentGroup=intercept_deployment_group,
)
# TODO(b/391304673): Remove this check once the field is
# available in BETA and V1.
# BETA API doesn't have the new field yet, so don't assign it. b/381837549
if hasattr(endpoint_group, 'description'):
endpoint_group.description = description
create_request = self.messages.NetworksecurityProjectsLocationsInterceptEndpointGroupsCreateRequest(
interceptEndpointGroup=endpoint_group,
interceptEndpointGroupId=endpoint_group_id,
parent=parent,
)
return self._endpoint_group_client.Create(create_request)
def DeleteEndpointGroup(self, name):
"""Calls the DeleteEndpointGroup API."""
delete_request = self.messages.NetworksecurityProjectsLocationsInterceptEndpointGroupsDeleteRequest(
name=name
)
return self._endpoint_group_client.Delete(delete_request)
def UpdateEndpointGroup(
self,
name,
description,
update_fields,
):
"""Calls the UpdateEndpointGroup API.
Args:
name: The name of the Endpoint Group to update.
description: The description of the Endpoint Group.
update_fields: A dictionary of the fields to update mapped to their new
values.
Returns:
Operation ref to track the long-running process.
"""
endpoint_group = self.messages.InterceptEndpointGroup(
labels=update_fields.get('labels', None),
)
# v1 API doesn't have the new field yet, so don't assign it.
if hasattr(endpoint_group, 'description'):
endpoint_group.description = description
update_request = self.messages.NetworksecurityProjectsLocationsInterceptEndpointGroupsPatchRequest(
name=name,
interceptEndpointGroup=endpoint_group,
updateMask=','.join(update_fields.keys())
)
return self._endpoint_group_client.Patch(update_request)
def DescribeEndpointGroup(self, name):
"""Calls the GetEndpointGroup API."""
get_request = self.messages.NetworksecurityProjectsLocationsInterceptEndpointGroupsGetRequest(
name=name
)
return self._endpoint_group_client.Get(get_request)
def ListEndpointGroups(
self, parent, limit=None, page_size=None, list_filter=None
):
"""Calls the ListEndpointGroups API."""
list_request = self.messages.NetworksecurityProjectsLocationsInterceptEndpointGroupsListRequest(
parent=parent, filter=list_filter
)
return list_pager.YieldFromList(
self._endpoint_group_client,
list_request,
batch_size=page_size,
limit=limit,
field='interceptEndpointGroups',
batch_size_attribute='pageSize',
)
def GetOperationRef(self, operation):
"""Converts an Operation to a Resource that can be used with `waiter.WaitFor`."""
return self._resource_parser.ParseRelativeName(
operation.name, 'networksecurity.projects.locations.operations'
)
def WaitForOperation(
self,
operation_ref,
message,
has_result=True,
max_wait=datetime.timedelta(seconds=600),
):
"""Waits for an operation to complete.
Polls the Network Security Operation service until the operation completes,
fails, or max_wait_seconds elapses.
Args:
operation_ref: A Resource created by GetOperationRef describing the
Operation.
message: The message to display to the user while they wait.
has_result: If True, the function will return the target of the operation
(the Intercept Endpoint Group) when it completes. If False, nothing will
be returned (useful for Delete operations)
max_wait: The time to wait for the operation to succeed before timing out.
Returns:
if has_result = True, an Endpoint Group entity.
Otherwise, None.
"""
if has_result:
poller = waiter.CloudOperationPoller(
self._endpoint_group_client, self._operations_client
)
else:
poller = waiter.CloudOperationPollerNoResources(self._operations_client)
return waiter.WaitFor(
poller,
operation_ref,
message,
max_wait_ms=int(max_wait.total_seconds()) * 1000,
)

View File

@@ -0,0 +1,14 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

View File

@@ -0,0 +1,241 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""API wrapper for `gcloud network-security mirroring-deployment-groups` commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import datetime
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.api_lib.util import waiter
from googlecloudsdk.calliope import base
from googlecloudsdk.core import resources
_API_VERSION_FOR_TRACK = {
base.ReleaseTrack.ALPHA: 'v1alpha1',
base.ReleaseTrack.BETA: 'v1beta1',
base.ReleaseTrack.GA: 'v1',
}
_API_NAME = 'networksecurity'
def GetMessagesModule(release_track=base.ReleaseTrack.ALPHA):
api_version = GetApiVersion(release_track)
return apis.GetMessagesModule(_API_NAME, api_version)
def GetClientInstance(release_track=base.ReleaseTrack.ALPHA):
api_version = GetApiVersion(release_track)
return apis.GetClientInstance(_API_NAME, api_version)
def GetEffectiveApiEndpoint(release_track=base.ReleaseTrack.ALPHA):
api_version = GetApiVersion(release_track)
return apis.GetEffectiveApiEndpoint(_API_NAME, api_version)
def GetApiVersion(release_track=base.ReleaseTrack.ALPHA):
return _API_VERSION_FOR_TRACK.get(release_track)
class Client:
"""API client for Mirroring Deployment Groups commands.
Attributes:
messages: API messages class, The Mirroring Deployment Groups messages.
"""
def __init__(self, release_track):
self._client = GetClientInstance(release_track)
self._deployment_group_client = (
self._client.projects_locations_mirroringDeploymentGroups
)
self._operations_client = self._client.projects_locations_operations
self.messages = GetMessagesModule(release_track)
self._resource_parser = resources.Registry()
self._resource_parser.RegisterApiByName(
_API_NAME, GetApiVersion(release_track)
)
def CreateDeploymentGroup(
self,
deployment_group_id: str,
parent: str,
network: str,
description: str,
labels=None,
):
"""Calls the CreateDeploymentGroup API.
Args:
deployment_group_id: str, the id of the mirroring deployment group.
parent: str, the parent resource name.
network: str, the network used for all group deployments.
description: str, the description of the mirroring deployment group.
labels: LabelsValue, optional labels as key-value pairs.
Returns:
Operation ref to track the long-running process.
"""
deployment_group = self.messages.MirroringDeploymentGroup(
labels=labels,
network=network,
description=description,
)
create_request = self.messages.NetworksecurityProjectsLocationsMirroringDeploymentGroupsCreateRequest(
mirroringDeploymentGroup=deployment_group,
mirroringDeploymentGroupId=deployment_group_id,
parent=parent,
)
return self._deployment_group_client.Create(create_request)
def DeleteDeploymentGroup(self, name):
"""Calls the DeleteDeploymentGroup API.
Args:
name: str, the name of the mirroring deployment group.
Returns:
Operation ref to track the long-running process.
"""
delete_request = self.messages.NetworksecurityProjectsLocationsMirroringDeploymentGroupsDeleteRequest(
name=name
)
return self._deployment_group_client.Delete(delete_request)
def UpdateDeploymentGroup(
self,
name,
description,
update_fields,
):
"""Calls the UpdateDeploymentGroup API.
Args:
name: str, the name of the mirroring deployment group.
description: str, the description of the mirroring deployment group.
update_fields: A dictionary of fields to update mapped to their new
values.
Returns:
Operation ref to track the long-running process.
"""
dg = self.messages.MirroringDeploymentGroup(
labels=update_fields.get('labels', None),
description=description,
)
update_request = self.messages.NetworksecurityProjectsLocationsMirroringDeploymentGroupsPatchRequest(
name=name,
mirroringDeploymentGroup=dg,
updateMask=','.join(update_fields.keys()),
)
return self._deployment_group_client.Patch(update_request)
def DescribeDeploymentGroup(self, name):
"""Calls the GetDeploymentGroup API.
Args:
name: str, the name of the mirroring deployment group.
Returns:
The mirroring deployment group object.
"""
get_request = self.messages.NetworksecurityProjectsLocationsMirroringDeploymentGroupsGetRequest(
name=name
)
return self._deployment_group_client.Get(get_request)
def ListDeploymentGroups(
self, parent, limit=None, page_size=None, list_filter=None
):
"""Calls the ListDeploymentGroups API.
Args:
parent: str, the parent resource name.
limit: int, optional limit for the number of results.
page_size: int, optional page size for the results.
list_filter: str, optional filter for the results.
Returns:
A generator yielding mirroring deployment groups.
"""
list_request = self.messages.NetworksecurityProjectsLocationsMirroringDeploymentGroupsListRequest(
parent=parent, filter=list_filter
)
return list_pager.YieldFromList(
self._deployment_group_client,
list_request,
batch_size=page_size,
limit=limit,
field='mirroringDeploymentGroups',
batch_size_attribute='pageSize',
)
def GetOperationRef(self, operation):
"""Converts an Operation to a Resource that can be used with `waiter.WaitFor`.
Args:
operation: The operation object.
Returns:
A Resource describing the operation.
"""
return self._resource_parser.ParseRelativeName(
operation.name, 'networksecurity.projects.locations.operations'
)
def WaitForOperation(
self,
operation_ref,
message,
has_result=True,
max_wait=datetime.timedelta(seconds=600),
):
"""Waits for an operation to complete.
Polls the Firewall Plus Operation service until the operation completes,
fails, or max_wait_seconds elapses.
Args:
operation_ref: A Resource created by GetOperationRef describing the
operation.
message: str, the message to display to the user while they wait.
has_result: bool, if True, returns the target of the operation when it
completes.
max_wait: datetime.timedelta, the maximum time to wait for the operation
to succeed.
Returns:
if has_result = True, a MirroringDeploymentGroup entity. Otherwise, None.
"""
if has_result:
poller = waiter.CloudOperationPoller(
self._deployment_group_client, self._operations_client
)
else:
poller = waiter.CloudOperationPollerNoResources(self._operations_client)
return waiter.WaitFor(
poller,
operation_ref,
message,
max_wait_ms=int(max_wait.total_seconds()) * 1000,
)

View File

@@ -0,0 +1,14 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

View File

@@ -0,0 +1,218 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""API wrapper for `gcloud network-security mirroring-deployments` commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import datetime
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.api_lib.util import waiter
from googlecloudsdk.calliope import base
from googlecloudsdk.core import resources
_API_VERSION_FOR_TRACK = {
base.ReleaseTrack.ALPHA: 'v1alpha1',
base.ReleaseTrack.BETA: 'v1beta1',
base.ReleaseTrack.GA: 'v1',
}
_API_NAME = 'networksecurity'
def GetMessagesModule(release_track=base.ReleaseTrack.ALPHA):
api_version = GetApiVersion(release_track)
return apis.GetMessagesModule(_API_NAME, api_version)
def GetClientInstance(release_track=base.ReleaseTrack.ALPHA):
api_version = GetApiVersion(release_track)
return apis.GetClientInstance(_API_NAME, api_version)
def GetEffectiveApiEndpoint(release_track=base.ReleaseTrack.ALPHA):
api_version = GetApiVersion(release_track)
return apis.GetEffectiveApiEndpoint(_API_NAME, api_version)
def GetApiVersion(release_track=base.ReleaseTrack.ALPHA):
return _API_VERSION_FOR_TRACK.get(release_track)
class Client:
"""API client for Mirroring Deployments commands.
Attributes:
messages: API messages class, The Network Security API messages.
"""
def __init__(self, release_track):
self._client = GetClientInstance(release_track)
self._deployments_client = (
self._client.projects_locations_mirroringDeployments
)
self._operations_client = self._client.projects_locations_operations
self.messages = GetMessagesModule(release_track)
self._resource_parser = resources.Registry()
self._resource_parser.RegisterApiByName(
_API_NAME, GetApiVersion(release_track)
)
def CreateDeployment(
self,
parent,
forwarding_rule,
mirroring_deployment_group,
description,
deployment_id=None,
labels=None,
):
"""Calls the CreateMirroringDeployment API.
Args:
parent: The parent of the deployment, e.g.
"projects/myproj/locations/us-central1"
forwarding_rule: The forwarding rule of the deployment, e.g.
"projects/myproj/regions/us-central1/forwardingRules/my-rule"
mirroring_deployment_group: The deployment group of the deployment, e.g.
"projects/myproj/locations/global/mirroringDeploymentGroups/my-group"
description: The description of the deployment.
deployment_id: The ID of the deployment, e.g. "my-deployment".
labels: A dictionary with the labels of the deployment.
Returns:
NetworksecurityProjectsLocationsMirroringDeploymentsCreateResponse
"""
deployment = self.messages.MirroringDeployment(
forwardingRule=forwarding_rule,
mirroringDeploymentGroup=mirroring_deployment_group,
labels=labels,
description=description,
)
create_request = self.messages.NetworksecurityProjectsLocationsMirroringDeploymentsCreateRequest(
mirroringDeployment=deployment,
mirroringDeploymentId=deployment_id,
parent=parent,
)
return self._deployments_client.Create(create_request)
def DeleteDeployment(self, name):
"""Calls the DeleteMirroringDeployment API."""
delete_request = self.messages.NetworksecurityProjectsLocationsMirroringDeploymentsDeleteRequest(
name=name
)
return self._deployments_client.Delete(delete_request)
def UpdateDeployment(
self,
name,
description,
update_fields,
):
"""Calls the UpdateMirroringDeployment API.
Args:
name: The name of the deployment.
description: The description of the deployment.
update_fields: A dictionary of the fields to update mapped to their new
values.
Returns:
Operation ref to track the long-running process.
"""
deployment = self.messages.MirroringDeployment(
labels=update_fields.get('labels', None),
description=description,
)
update_request = self.messages.NetworksecurityProjectsLocationsMirroringDeploymentsPatchRequest(
name=name,
mirroringDeployment=deployment,
updateMask=','.join(update_fields.keys())
)
return self._deployments_client.Patch(update_request)
def DescribeDeployment(self, name):
"""Calls the GetMirroringDeployment API."""
get_request = self.messages.NetworksecurityProjectsLocationsMirroringDeploymentsGetRequest(
name=name
)
return self._deployments_client.Get(get_request)
def ListDeployments(
self, parent, limit=None, page_size=None, list_filter=None
):
"""Calls the ListMirroringDeployments API."""
list_request = self.messages.NetworksecurityProjectsLocationsMirroringDeploymentsListRequest(
parent=parent, filter=list_filter
)
return list_pager.YieldFromList(
self._deployments_client,
list_request,
batch_size=page_size,
limit=limit,
field='mirroringDeployments',
batch_size_attribute='pageSize',
)
def GetOperationRef(self, operation):
"""Converts an Operation to a Resource to use with `waiter.WaitFor`."""
return self._resource_parser.ParseRelativeName(
operation.name, 'networksecurity.projects.locations.operations'
)
def WaitForOperation(
self,
operation_ref,
message,
has_result=True,
max_wait=datetime.timedelta(seconds=600),
):
"""Waits for an operation to complete.
Polls the Network Security Operation service until the operation completes,
fails, or max_wait_seconds elapses.
Args:
operation_ref: A Resource created by GetOperationRef describing the
Operation.
message: The message to display to the user while they wait.
has_result: If True, the function will return the target of the operation
(the Mirroring Deployment) when it completes. If False, nothing will be
returned (useful for Delete operations).
max_wait: The time to wait for the operation to succeed before timing out.
Returns:
If has_result = True, a Mirroring Deployment entity.
Otherwise, None.
"""
if has_result:
poller = waiter.CloudOperationPoller(
self._deployments_client, self._operations_client
)
else:
poller = waiter.CloudOperationPollerNoResources(self._operations_client)
return waiter.WaitFor(
poller,
operation_ref,
message,
max_wait_ms=int(max_wait.total_seconds()) * 1000,
)

View File

@@ -0,0 +1,14 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

View File

@@ -0,0 +1,189 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""API wrapper for `gcloud network-security mirroring-endpoint-group-associations` commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import datetime
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.api_lib.util import waiter
from googlecloudsdk.calliope import base
from googlecloudsdk.core import resources
_API_VERSION_FOR_TRACK = {
base.ReleaseTrack.ALPHA: 'v1alpha1',
base.ReleaseTrack.BETA: 'v1beta1',
base.ReleaseTrack.GA: 'v1',
}
_API_NAME = 'networksecurity'
def GetMessagesModule(release_track=base.ReleaseTrack.ALPHA):
api_version = GetApiVersion(release_track)
return apis.GetMessagesModule(_API_NAME, api_version)
def GetClientInstance(release_track=base.ReleaseTrack.ALPHA):
api_version = GetApiVersion(release_track)
return apis.GetClientInstance(_API_NAME, api_version)
def GetEffectiveApiEndpoint(release_track=base.ReleaseTrack.ALPHA):
api_version = GetApiVersion(release_track)
return apis.GetEffectiveApiEndpoint(_API_NAME, api_version)
def GetApiVersion(release_track=base.ReleaseTrack.ALPHA):
return _API_VERSION_FOR_TRACK.get(release_track)
class Client:
"""API client for Mirroring Endpoint Group Association commands.
Attributes:
messages: API messages class, The Mirroring Endpoint Group Association API
messages.
"""
def __init__(self, release_track):
self._client = GetClientInstance(release_track)
self._association_client = (
self._client.projects_locations_mirroringEndpointGroupAssociations
)
self._operations_client = self._client.projects_locations_operations
self.messages = GetMessagesModule(release_track)
self._resource_parser = resources.Registry()
self._resource_parser.RegisterApiByName(
_API_NAME, GetApiVersion(release_track)
)
def CreateEndpointGroupAssociation(
self,
association_id,
parent,
network,
mirroring_endpoint_group,
labels=None,
):
"""Calls the CreateEndpointGroupAssociation API."""
association = self.messages.MirroringEndpointGroupAssociation(
labels=labels,
network=network,
mirroringEndpointGroup=mirroring_endpoint_group,
)
create_request = self.messages.NetworksecurityProjectsLocationsMirroringEndpointGroupAssociationsCreateRequest(
mirroringEndpointGroupAssociation=association,
mirroringEndpointGroupAssociationId=association_id,
parent=parent,
)
return self._association_client.Create(create_request)
def DeleteEndpointGroupAssociation(self, name):
"""Calls the DeleteEndpointGroupAssociation API."""
delete_request = self.messages.NetworksecurityProjectsLocationsMirroringEndpointGroupAssociationsDeleteRequest(
name=name
)
return self._association_client.Delete(delete_request)
def UpdateEndpointGroupAssociation(
self,
name,
update_fields,
):
"""Calls the UpdateEndpointGroupAssociation API."""
association = self.messages.MirroringEndpointGroupAssociation(
labels=update_fields.get('labels', None)
)
update_request = self.messages.NetworksecurityProjectsLocationsMirroringEndpointGroupAssociationsPatchRequest(
name=name,
mirroringEndpointGroupAssociation=association,
updateMask=','.join(update_fields.keys()),
)
return self._association_client.Patch(update_request)
def DescribeEndpointGroupAssociation(self, name):
"""Calls the GetEndpointGroupAssociation API."""
get_request = self.messages.NetworksecurityProjectsLocationsMirroringEndpointGroupAssociationsGetRequest(
name=name
)
return self._association_client.Get(get_request)
def ListEndpointGroupAssociations(
self, parent, limit=None, page_size=None, list_filter=None
):
"""Calls the ListEndpointGroupAssociations API."""
list_request = self.messages.NetworksecurityProjectsLocationsMirroringEndpointGroupAssociationsListRequest(
parent=parent, filter=list_filter
)
return list_pager.YieldFromList(
self._association_client,
list_request,
batch_size=page_size,
limit=limit,
field='mirroringEndpointGroupAssociations',
batch_size_attribute='pageSize',
)
def GetOperationRef(self, operation):
"""Converts an Operation to a Resource that can be used with `waiter.WaitFor`."""
return self._resource_parser.ParseRelativeName(
operation.name, 'networksecurity.projects.locations.operations'
)
def WaitForOperation(
self,
operation_ref,
message,
has_result=True,
max_wait=datetime.timedelta(seconds=600),
):
"""Waits for an operation to complete.
Polls the Mirroring Endpoint Group Association Operation service until the
operation completes,
fails, or max_wait_seconds elapses.
Args:
operation_ref: A Resource created by GetOperationRef describing the
Operation.
message: The message to display to the user while they wait.
has_result: If True, the function will return the target of the operation
(the Mirroring Endpoint Group Association) when it completes. If False,
nothing will be returned (useful for Delete operations)
max_wait: The time to wait for the operation to succeed before timing out.
Returns:
if has_result = True, an Association entity.
Otherwise, None.
"""
if has_result:
poller = waiter.CloudOperationPoller(
self._association_client, self._operations_client
)
else:
poller = waiter.CloudOperationPollerNoResources(self._operations_client)
return waiter.WaitFor(
poller,
operation_ref,
message,
max_wait_ms=int(max_wait.total_seconds()) * 1000,
)

View File

@@ -0,0 +1,14 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

View File

@@ -0,0 +1,235 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""API wrapper for `gcloud network-security mirroring-endpoint-groups` commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import datetime
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.api_lib.util import waiter
from googlecloudsdk.calliope import base
from googlecloudsdk.core import resources
_API_VERSION_FOR_TRACK = {
base.ReleaseTrack.ALPHA: 'v1alpha1',
base.ReleaseTrack.BETA: 'v1beta1',
base.ReleaseTrack.GA: 'v1',
}
_API_NAME = 'networksecurity'
_PACKET_BROKER_SUPPORTED = (base.ReleaseTrack.ALPHA,)
def GetMessagesModule(release_track=base.ReleaseTrack.ALPHA):
api_version = GetApiVersion(release_track)
return apis.GetMessagesModule(_API_NAME, api_version)
def GetClientInstance(release_track=base.ReleaseTrack.ALPHA):
api_version = GetApiVersion(release_track)
return apis.GetClientInstance(_API_NAME, api_version)
def GetEffectiveApiEndpoint(release_track=base.ReleaseTrack.ALPHA):
api_version = GetApiVersion(release_track)
return apis.GetEffectiveApiEndpoint(_API_NAME, api_version)
def GetApiVersion(release_track=base.ReleaseTrack.ALPHA):
return _API_VERSION_FOR_TRACK.get(release_track)
class Client:
"""API client for Mirroring Endpoint Groups commands.
Attributes:
messages: API messages class, The Mirroring Endpoint Groups API messages.
"""
def __init__(self, release_track):
self._release_track = release_track
self._client = GetClientInstance(release_track)
self._endpoint_group_client = (
self._client.projects_locations_mirroringEndpointGroups
)
self._operations_client = self._client.projects_locations_operations
self.messages = GetMessagesModule(release_track)
self._resource_parser = resources.Registry()
self._resource_parser.RegisterApiByName(
_API_NAME, GetApiVersion(release_track)
)
def CreateEndpointGroup(
self,
endpoint_group_id,
parent,
deployment_groups,
description,
endpoint_group_type='DIRECT',
labels=None,
):
"""Calls the CreateEndpointGroup API.
Args:
endpoint_group_id: The ID of the Endpoint Group to create.
parent: The parent of the Endpoint Group to create.
deployment_groups: The Mirroring Deployment Group(s) to associate with the
Endpoint Group. Can be a single string or a list of strings.
description: Description of the Endpoint Group.
endpoint_group_type: Type of the Endpoint Group (DIRECT or BROKER).
labels: Labels to apply to the Endpoint Group.
Returns:
Operation ref to track the long-running process.
"""
endpoint_group = self.messages.MirroringEndpointGroup(
labels=labels,
description=description,
)
if self._release_track in _PACKET_BROKER_SUPPORTED:
if not endpoint_group_type:
endpoint_group_type = 'DIRECT'
endpoint_group.type = (
self.messages.MirroringEndpointGroup.TypeValueValuesEnum(
endpoint_group_type
)
)
if endpoint_group_type == 'BROKER':
if isinstance(deployment_groups, list):
endpoint_group.mirroringDeploymentGroups = deployment_groups
else:
endpoint_group.mirroringDeploymentGroups = [deployment_groups]
elif endpoint_group_type == 'DIRECT':
endpoint_group.mirroringDeploymentGroup = deployment_groups
else:
raise ValueError(
f'Unsupported endpoint group type: {endpoint_group_type}'
)
else:
endpoint_group.mirroringDeploymentGroup = deployment_groups
create_request = self.messages.NetworksecurityProjectsLocationsMirroringEndpointGroupsCreateRequest(
mirroringEndpointGroup=endpoint_group,
mirroringEndpointGroupId=endpoint_group_id,
parent=parent,
)
return self._endpoint_group_client.Create(create_request)
def DeleteEndpointGroup(self, name):
"""Calls the DeleteEndpointGroup API."""
delete_request = self.messages.NetworksecurityProjectsLocationsMirroringEndpointGroupsDeleteRequest(
name=name
)
return self._endpoint_group_client.Delete(delete_request)
def UpdateEndpointGroup(self, name, description, update_fields):
"""Calls the UpdateEndpointGroup API.
Args:
name: The name of the Endpoint Group to update.
description: Description of the Endpoint Group.
update_fields: A dictionary of the fields to update mapped to their new
values.
Returns:
Operation ref to track the long-running process.
"""
endpoint_group = self.messages.MirroringEndpointGroup(
labels=update_fields.get('labels', None),
description=description,
)
update_request = self.messages.NetworksecurityProjectsLocationsMirroringEndpointGroupsPatchRequest(
name=name,
mirroringEndpointGroup=endpoint_group,
updateMask=','.join(update_fields.keys()),
)
return self._endpoint_group_client.Patch(update_request)
def DescribeEndpointGroup(self, name):
"""Calls the GetEndpointGroup API."""
get_request = self.messages.NetworksecurityProjectsLocationsMirroringEndpointGroupsGetRequest(
name=name
)
return self._endpoint_group_client.Get(get_request)
def ListEndpointGroups(
self, parent, limit=None, page_size=None, list_filter=None
):
"""Calls the ListEndpointGroups API."""
list_request = self.messages.NetworksecurityProjectsLocationsMirroringEndpointGroupsListRequest(
parent=parent, filter=list_filter
)
return list_pager.YieldFromList(
self._endpoint_group_client,
list_request,
batch_size=page_size,
limit=limit,
field='mirroringEndpointGroups',
batch_size_attribute='pageSize',
)
def GetOperationRef(self, operation):
"""Converts an Operation to a Resource that can be used with `waiter.WaitFor`."""
return self._resource_parser.ParseRelativeName(
operation.name, 'networksecurity.projects.locations.operations'
)
def WaitForOperation(
self,
operation_ref,
message,
has_result=True,
max_wait=datetime.timedelta(seconds=600),
):
"""Waits for an operation to complete.
Polls the Network Security Operation service until the operation completes,
fails, or max_wait_seconds elapses.
Args:
operation_ref: A Resource created by GetOperationRef describing the
Operation.
message: The message to display to the user while they wait.
has_result: If True, the function will return the target of the operation
(the Mirroring Endpoint Group) when it completes. If False, nothing will
be returned (useful for Delete operations)
max_wait: The time to wait for the operation to succeed before timing out.
Returns:
if has_result = True, an Endpoint Group entity.
Otherwise, None.
"""
if has_result:
poller = waiter.CloudOperationPoller(
self._endpoint_group_client, self._operations_client
)
else:
poller = waiter.CloudOperationPollerNoResources(self._operations_client)
return waiter.WaitFor(
poller,
operation_ref,
message,
max_wait_ms=int(max_wait.total_seconds()) * 1000,
)

View File

@@ -0,0 +1,14 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

View File

@@ -0,0 +1,192 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""API wrapper for `gcloud network-security security-profile-groups` commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import datetime
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.api_lib.util import waiter
from googlecloudsdk.calliope import base
from googlecloudsdk.core import resources
_API_VERSION_FOR_TRACK = {
base.ReleaseTrack.ALPHA: 'v1alpha1',
base.ReleaseTrack.BETA: 'v1beta1',
base.ReleaseTrack.GA: 'v1',
}
_API_NAME = 'networksecurity'
def GetMessagesModule(release_track=base.ReleaseTrack.GA):
api_version = _API_VERSION_FOR_TRACK.get(release_track)
return apis.GetMessagesModule(_API_NAME, api_version)
def GetClientInstance(release_track=base.ReleaseTrack.GA):
api_version = _API_VERSION_FOR_TRACK.get(release_track)
return apis.GetClientInstance(_API_NAME, api_version)
def GetApiBaseUrl(release_track=base.ReleaseTrack.GA):
api_version = _API_VERSION_FOR_TRACK.get(release_track)
return resources.GetApiBaseUrlOrThrow(_API_NAME, api_version)
def GetApiVersion(release_track=base.ReleaseTrack.GA):
return _API_VERSION_FOR_TRACK.get(release_track)
class Client:
"""API client for security profile group commands."""
def __init__(self, release_track):
self._client = GetClientInstance(release_track)
self._security_profile_group_client = (
self._client.organizations_locations_securityProfileGroups
)
self._operations_client = self._client.organizations_locations_operations
self._locations_client = self._client.organizations_locations
self.messages = GetMessagesModule(release_track)
self._resource_parser = resources.Registry()
self.api_version = _API_VERSION_FOR_TRACK.get(release_track)
self._resource_parser.RegisterApiByName(
_API_NAME, _API_VERSION_FOR_TRACK.get(release_track)
)
def WaitForOperation(
self,
operation_ref,
message,
has_result=False,
max_wait=datetime.timedelta(seconds=600),
):
"""Waits for an operation to complete.
Polls the Network Security Operation service until the operation completes,
fails, or max_wait_seconds elapses.
Args:
operation_ref: A Resource created by GetOperationRef describing the
Operation.
message: The message to display to the user while they wait.
has_result: If True, the function will return the target of the operation
when it completes. If False, nothing will be returned.
max_wait: The time to wait for the operation to succeed before timing out.
Returns:
if has_result = True, a Security Profile Group entity.
Otherwise, None.
"""
if has_result:
poller = waiter.CloudOperationPoller(
self._security_profile_group_client, self._operations_client
)
else:
poller = waiter.CloudOperationPollerNoResources(self._operations_client)
response = waiter.WaitFor(
poller, operation_ref, message, max_wait_ms=max_wait.seconds * 1000
)
return response
def GetOperationsRef(self, operation):
"""Operations to Resource used for `waiter.WaitFor`."""
return self._resource_parser.ParseRelativeName(
operation.name,
'networksecurity.organizations.locations.operations',
False,
self.api_version,
)
def GetSecurityProfileGroup(self, security_profile_group_name):
"""Calls the Security Profile Group Get API.
Args:
security_profile_group_name: Fully specified Security Profile Group.
Returns:
Security Profile Group object.
"""
api_request = self.messages.NetworksecurityOrganizationsLocationsSecurityProfileGroupsGetRequest(
name=security_profile_group_name
)
return self._security_profile_group_client.Get(api_request)
def CreateSecurityProfileGroup(
self,
security_profile_group_name,
security_profile_group_id,
parent,
description,
threat_prevention_profile=None,
url_filtering_profile=None,
custom_mirroring_profile=None,
custom_intercept_profile=None,
labels=None,
):
"""Calls the Create Security Profile Group API."""
security_profile_group = self.messages.SecurityProfileGroup(
name=security_profile_group_name,
description=description,
threatPreventionProfile=threat_prevention_profile,
labels=labels,
)
if hasattr(security_profile_group, 'urlFilteringProfile'):
security_profile_group.urlFilteringProfile = url_filtering_profile
# v1 API doesn't have the new field yet, so don't assign it.
if hasattr(security_profile_group, 'customMirroringProfile'):
security_profile_group.customMirroringProfile = custom_mirroring_profile
if hasattr(security_profile_group, 'customInterceptProfile'):
security_profile_group.customInterceptProfile = custom_intercept_profile
api_request = self.messages.NetworksecurityOrganizationsLocationsSecurityProfileGroupsCreateRequest(
parent=parent,
securityProfileGroup=security_profile_group,
securityProfileGroupId=security_profile_group_id,
)
return self._security_profile_group_client.Create(api_request)
def UpdateSecurityProfileGroup(
self,
security_profile_group_name,
description,
threat_prevention_profile,
url_filtering_profile,
update_mask,
labels=None,
):
"""Calls the Patch Security Profile Group API."""
security_profile_group = self.messages.SecurityProfileGroup(
name=security_profile_group_name,
description=description,
threatPreventionProfile=threat_prevention_profile,
labels=labels,
)
if hasattr(security_profile_group, 'urlFilteringProfile'):
security_profile_group.urlFilteringProfile = url_filtering_profile
api_request = self.messages.NetworksecurityOrganizationsLocationsSecurityProfileGroupsPatchRequest(
name=security_profile_group_name,
securityProfileGroup=security_profile_group,
updateMask=update_mask,
)
return self._security_profile_group_client.Patch(api_request)

View File

@@ -0,0 +1,14 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

View File

@@ -0,0 +1,81 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""API wrapper for `gcloud network-security security-profiles custom-intercept` commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.network_security.security_profiles import sp_api
CUSTOM_INTERCEPT_PROFILE_TYPE = 'CUSTOM_INTERCEPT'
class Client(sp_api.Client):
"""API client for custom intercept commands."""
def GetCustomInterceptProfile(self, name):
"""Calls the Security Profile Get API to return the Intercept Profile.
Args:
name: Fully specified Security Profile.
Returns:
An etag and a CustominterceptProfile object,
or etag,None if the profile is not a Threat Prevention Profile.
"""
response = self.GetSecurityProfile(name)
if response.type != self._ParseSecurityProfileType(
CUSTOM_INTERCEPT_PROFILE_TYPE
):
return response.etag, None
return response.etag, response.customInterceptProfile
def ListCustomInterceptProfiles(self, parent, limit=None, page_size=None):
"""Calls the ListSecurityProfiles API, filtering by type."""
profiles = self.ListSecurityProfiles(parent, limit, page_size)
return [
profile
for profile in profiles
if profile.type
== self._ParseSecurityProfileType(CUSTOM_INTERCEPT_PROFILE_TYPE)
]
def CreateCustomInterceptProfile(
self,
sp_id,
parent,
description,
labels,
intercept_endpoint_group,
):
"""Calls the Create Security Profile API to create a Custom Intercept Profile."""
profile = self.messages.SecurityProfile(
type=self._ParseSecurityProfileType(CUSTOM_INTERCEPT_PROFILE_TYPE),
customInterceptProfile=self.messages.CustomInterceptProfile(
interceptEndpointGroup=intercept_endpoint_group
),
description=description,
labels=labels,
)
return self._security_profile_client.Create(
self.messages.NetworksecurityOrganizationsLocationsSecurityProfilesCreateRequest(
parent=parent,
securityProfile=profile,
securityProfileId=sp_id,
)
)

View File

@@ -0,0 +1,140 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""API wrapper for `gcloud network-security security-profiles custom-mirroring` commands."""
from __future__ import absolute_import
from __future__ import annotations
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.network_security.security_profiles import sp_api
CUSTOM_MIRRORING_PROFILE_TYPE = 'CUSTOM_MIRRORING'
class Client(sp_api.Client):
"""API client for custom mirroring commands."""
def GetCustomMirroringProfile(self, name):
"""Calls the Security Profile Get API to return the Mirroring Profile.
Args:
name: Fully specified Security Profile.
Returns:
An etag and a CustomMirroringProfile object,
or etag,None if the profile is not a Threat Prevention Profile.
"""
response = self.GetSecurityProfile(name)
if response.type != self._ParseSecurityProfileType(
CUSTOM_MIRRORING_PROFILE_TYPE
):
return response.etag, None
return response.etag, response.customMirroringProfile
def ListCustomMirroringProfiles(self, parent, limit=None, page_size=None):
"""Calls the ListSecurityProfiles API, filtering by type."""
profiles = self.ListSecurityProfiles(parent, limit, page_size)
return [
profile
for profile in profiles
if profile.type
== self._ParseSecurityProfileType(CUSTOM_MIRRORING_PROFILE_TYPE)
]
def CreateCustomMirroringProfile(
self,
sp_id,
parent,
description,
labels,
mirroring_endpoint_group,
mirroring_deployment_groups,
):
"""Calls the Create Security Profile API to create a Custom Mirroring Profile."""
profile = self.messages.SecurityProfile(
type=self._ParseSecurityProfileType(CUSTOM_MIRRORING_PROFILE_TYPE),
customMirroringProfile=self.messages.CustomMirroringProfile(
mirroringEndpointGroup=mirroring_endpoint_group
),
description=description,
labels=labels,
)
# TODO(b/439516438) - remove hasattr check and move into main instantiation
# above once all API versions have the field.
if hasattr(profile.customMirroringProfile, 'mirroringDeploymentGroups'):
profile.customMirroringProfile.mirroringDeploymentGroups = (
mirroring_deployment_groups or []
)
return self._security_profile_client.Create(
self.messages.NetworksecurityOrganizationsLocationsSecurityProfilesCreateRequest(
parent=parent,
securityProfile=profile,
securityProfileId=sp_id,
)
)
def UpdateCustomMirroringProfile(
self,
name,
description: str | None = None,
labels: dict[str, str] | None = None,
deployment_groups: list[str] | None = None,
):
"""Calls the Update Security Profile API to update a Custom Mirroring Profile.
Args:
name: The name of the Security Profile, e.g.
"organizations/123/locations/global/securityProfiles/my-profile".
description: The user-specified description of the Security Profile. None
= no change.
labels: The labels of the Security Profile. None = no change.
deployment_groups: The list of deployment groups associated with the
profile. None = no change.
Returns:
Updated Security Profile object.
"""
updated_sp = self.messages.SecurityProfile(
customMirroringProfile=self.messages.CustomMirroringProfile()
)
update_mask = []
if description:
updated_sp.description = description
update_mask.append('description')
if labels:
updated_sp.labels = labels
update_mask.append('labels')
if deployment_groups:
# TODO(b/439516438) - remove hasattr check and move into main
# instantiation above once all API versions have the field.
if hasattr(
updated_sp.customMirroringProfile, 'mirroringDeploymentGroups'
):
updated_sp.customMirroringProfile.mirroringDeploymentGroups = (
deployment_groups
)
update_mask.append('customMirroringProfile.mirroringDeploymentGroups')
api_request = self.messages.NetworksecurityOrganizationsLocationsSecurityProfilesPatchRequest(
name=name,
securityProfile=updated_sp,
updateMask=','.join(update_mask),
)
return self._security_profile_client.Patch(api_request)

View File

@@ -0,0 +1,190 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""API wrapper for `gcloud network-security security-profiles` commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import abc
import datetime
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.api_lib.util import waiter
from googlecloudsdk.calliope import base
from googlecloudsdk.core import resources
_API_VERSION_FOR_TRACK = {
base.ReleaseTrack.ALPHA: 'v1alpha1',
base.ReleaseTrack.BETA: 'v1beta1',
base.ReleaseTrack.GA: 'v1',
}
_API_NAME = 'networksecurity'
def GetMessagesModule(release_track=base.ReleaseTrack.GA):
api_version = GetApiVersion(release_track)
return apis.GetMessagesModule(_API_NAME, api_version)
def GetClientInstance(release_track=base.ReleaseTrack.GA):
api_version = GetApiVersion(release_track)
return apis.GetClientInstance(_API_NAME, api_version)
def GetApiBaseUrl(release_track=base.ReleaseTrack.GA):
api_version = GetApiVersion(release_track)
return resources.GetApiBaseUrlOrThrow(_API_NAME, api_version)
def GetApiVersion(release_track=base.ReleaseTrack.GA):
return _API_VERSION_FOR_TRACK.get(release_track)
def GetEffectiveApiEndpoint(release_track=base.ReleaseTrack.ALPHA):
api_version = GetApiVersion(release_track)
return apis.GetEffectiveApiEndpoint(_API_NAME, api_version)
class Client(abc.ABC):
"""API client for all security profile commands."""
def __init__(self, release_track):
self._client = GetClientInstance(release_track)
self._security_profile_client = (
self._client.organizations_locations_securityProfiles
)
self._operations_client = self._client.organizations_locations_operations
self._locations_client = self._client.organizations_locations
self.messages = GetMessagesModule(release_track)
self._resource_parser = resources.Registry()
self.api_version = _API_VERSION_FOR_TRACK.get(release_track)
self._resource_parser.RegisterApiByName(
_API_NAME, _API_VERSION_FOR_TRACK.get(release_track)
)
def _ParseSecurityProfileType(self, profile_type):
return self.messages.SecurityProfile.TypeValueValuesEnum.lookup_by_name(
profile_type
)
def GetSecurityProfile(self, name):
"""Calls the Security Profile Get API to return the security profile object.
Args:
name: Fully specified Security Profile.
Returns:
Security Profile object.
"""
api_request = self.messages.NetworksecurityOrganizationsLocationsSecurityProfilesGetRequest(
name=name
)
return self._security_profile_client.Get(api_request)
def GetOperationsRef(self, operation):
"""Operations to Resource used for `waiter.WaitFor`."""
return self._resource_parser.ParseRelativeName(
operation.name,
'networksecurity.organizations.locations.operations',
False,
self.api_version,
)
def WaitForOperation(
self,
operation_ref,
message,
has_result=False,
max_wait=datetime.timedelta(seconds=600),
):
"""Waits for an operation to complete.
Polls the Network Security Operation service until the operation completes,
fails, or max_wait_seconds elapses.
Args:
operation_ref: A Resource created by GetOperationRef describing the
Operation.
message: The message to display to the user while they wait.
has_result: If True, the function will return the target of the operation
when it completes. If False, nothing will be returned.
max_wait: The time to wait for the operation to succeed before timing out.
Returns:
if has_result = True, a Security Profile entity.
Otherwise, None.
"""
if has_result:
poller = waiter.CloudOperationPoller(
self._security_profile_client, self._operations_client
)
else:
poller = waiter.CloudOperationPollerNoResources(self._operations_client)
response = waiter.WaitFor(
poller, operation_ref, message, max_wait_ms=max_wait.seconds * 1000
)
return response
def ListSecurityProfiles(
self,
parent,
limit=None,
page_size=None,
):
"""Calls the ListSecurityProfiles API."""
list_request = self.messages.NetworksecurityOrganizationsLocationsSecurityProfilesListRequest(
parent=parent
)
return list_pager.YieldFromList(
self._security_profile_client,
list_request,
batch_size=page_size,
limit=limit,
field='securityProfiles',
batch_size_attribute='pageSize',
)
def UpdateSecurityProfile(self, name, description=None, labels=None):
"""Calls the Update Security Profile API to update a Security Profile.
Args:
name: The name of the Security Profile, e.g.
"organizations/123/locations/global/securityProfiles/my-profile".
description: The user-specified description of the Security Profile.
labels: The labels of the Security Profile.
Returns:
Updated Security Profile object.
"""
updated_sp = self.messages.SecurityProfile()
update_mask = []
if description:
updated_sp.description = description
update_mask.append('description')
if labels:
updated_sp.labels = labels
update_mask.append('labels')
api_request = self.messages.NetworksecurityOrganizationsLocationsSecurityProfilesPatchRequest(
name=name,
securityProfile=updated_sp,
updateMask=','.join(update_mask),
)
return self._security_profile_client.Patch(api_request)

View File

@@ -0,0 +1,299 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""API wrapper for `gcloud network-security security-profiles threat-prevention-profiles` commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import encoding
from googlecloudsdk.api_lib.network_security.security_profiles import sp_api
THREAT_PREVENTION_PROFILE_TYPE = 'THREAT_PREVENTION'
class Client(sp_api.Client):
"""API client for threat prevention commands."""
def GetThreatPreventionProfile(self, name):
"""Calls the Security Profile Get API to return the TPP Profile.
Args:
name: Fully specified Security Profile.
Returns:
An etag and a Dict of existing Threat Prevention Profile configuration,
or etag,None if the profile is not a Threat Prevention Profile.
"""
response = self.GetSecurityProfile(name)
if response.type != self._ParseSecurityProfileType(
THREAT_PREVENTION_PROFILE_TYPE
):
return response.etag, None
if response.threatPreventionProfile is None:
return response.etag, {
'severityOverrides': [],
'threatOverrides': [],
'antivirusOverrides': [],
}
else:
profile = encoding.MessageToDict(response.threatPreventionProfile)
# If Threat Prevention Profile is empty, format the profile response.
if not any(profile):
return response.etag, {
'severityOverrides': [],
'threatOverrides': [],
'antivirusOverrides': [],
}
else:
if profile.get('antivirusOverrides') is None:
profile['antivirusOverrides'] = []
if profile.get('severityOverrides') is None:
profile['severityOverrides'] = []
if profile.get('threatOverrides') is None:
profile['threatOverrides'] = []
return response.etag, profile
def CheckOverridesExist(
self,
existing_threat_prevention_profile_object,
update_mask,
override,
):
"""Checks if override exists in the current threat prevention object.
Args:
existing_threat_prevention_profile_object: Existing Threat Prevention
Profile JSON object.
update_mask: String Arg specifying type of override which needs update.
override: The override object provided from the command line.
Returns:
A bool specifying if the override exists and index of the override in
existing_threat_prevention_profile_object if the override exists or None
is returned.
"""
update_field = ''
if update_mask == 'antivirusOverrides':
update_field = 'protocol'
if update_mask == 'severityOverrides':
update_field = 'severity'
elif update_mask == 'threatOverrides':
update_field = 'threatId'
for i in range(
0, len(existing_threat_prevention_profile_object.get(update_mask))
):
if existing_threat_prevention_profile_object.get(update_mask)[i].get(
update_field
) == override.get(update_field):
return True, i
return False, None
def UpdateThreatPreventionProfile(
self,
existing_threat_prevention_profile_object,
overrides,
update_mask,
operation_type,
):
"""Updates the existing threat_prevention_profile object.
Args:
existing_threat_prevention_profile_object: Existing Threat Prevention
Profile JSON object.
overrides: JSON object of overrides specified in command line.
update_mask: String Arg specifying type of override which needs update.
operation_type: String Arg specifying the type of operation which is
performed in this method.
Returns:
Modified Threat Prevention Profile JSON object.
"""
if operation_type == 'add_override':
for override in overrides:
does_override_exist, _ = self.CheckOverridesExist(
existing_threat_prevention_profile_object,
update_mask,
override,
)
if not does_override_exist:
existing_threat_prevention_profile_object.get(update_mask).extend(
[override]
)
return existing_threat_prevention_profile_object
elif operation_type == 'update_override':
for override in overrides:
does_override_exist, override_index = self.CheckOverridesExist(
existing_threat_prevention_profile_object,
update_mask,
override,
)
if does_override_exist:
existing_threat_prevention_profile_object.get(update_mask).pop(
override_index
)
existing_threat_prevention_profile_object.get(update_mask).extend(
[override]
)
return existing_threat_prevention_profile_object
def ModifyOverride(
self,
name,
overrides,
operation_type,
update_mask,
profile_type=THREAT_PREVENTION_PROFILE_TYPE,
labels=None,
):
"""Modify the existing threat prevention profile."""
etag, existing_threat_prevention_profile_object = (
self.GetThreatPreventionProfile(name)
)
updated_threat_prevention_profile_object = (
self.UpdateThreatPreventionProfile(
existing_threat_prevention_profile_object,
overrides,
update_mask,
operation_type,
)
)
if (
updated_threat_prevention_profile_object
== existing_threat_prevention_profile_object
):
update_mask = '*'
else:
update_mask = 'threatPreventionProfile'
# Calls the Security Profile Update API
# to add/update override to threat prevention profile object.
security_profile = self.messages.SecurityProfile(
name=name,
threatPreventionProfile=encoding.DictToMessage(
updated_threat_prevention_profile_object,
self.messages.ThreatPreventionProfile,
),
etag=etag,
type=self._ParseSecurityProfileType(profile_type),
labels=labels,
)
api_request = self.messages.NetworksecurityOrganizationsLocationsSecurityProfilesPatchRequest(
name=name,
securityProfile=security_profile,
updateMask=update_mask,
)
return self._security_profile_client.Patch(api_request)
def ListOverrides(self, name):
"""Calls the Security Profile Get API to list all Security Profile Overrides."""
api_request = self.messages.NetworksecurityOrganizationsLocationsSecurityProfilesGetRequest(
name=name
)
return self._security_profile_client.Get(api_request)
def DeleteOverride(
self,
name,
overrides,
update_mask,
profile_type=THREAT_PREVENTION_PROFILE_TYPE,
labels=None,
):
"""Delete the existing threat prevention profile override."""
etag, existing_threat_prevention_profile_object = (
self.GetThreatPreventionProfile(name)
)
if update_mask in existing_threat_prevention_profile_object:
update_field = ''
if update_mask == 'antivirusOverrides':
update_field = 'protocol'
if update_mask == 'severityOverrides':
update_field = 'severity'
elif update_mask == 'threatOverrides':
update_field = 'threatId'
for specified_override in overrides:
for i in range(
0, len(existing_threat_prevention_profile_object.get(update_mask))
):
if (
existing_threat_prevention_profile_object.get(update_mask)[i].get(
update_field
)
== specified_override
):
existing_threat_prevention_profile_object.get(update_mask).pop(i)
break
# Calls the Security Profile Update API
# to delete override of threat prevention profile object.
security_profile = self.messages.SecurityProfile(
name=name,
threatPreventionProfile=encoding.DictToMessage(
existing_threat_prevention_profile_object,
self.messages.ThreatPreventionProfile,
),
etag=etag,
type=self._ParseSecurityProfileType(profile_type),
labels=labels,
)
api_request = self.messages.NetworksecurityOrganizationsLocationsSecurityProfilesPatchRequest(
name=name,
securityProfile=security_profile,
updateMask='threatPreventionProfile',
)
return self._security_profile_client.Patch(api_request)
def CreateThreatPreventionProfile(
self,
name,
sp_id,
parent,
description,
labels=None,
):
"""Calls the SPG API to create a Threat Prevention Profile."""
profile = self.messages.SecurityProfile(
name=name,
type=self._ParseSecurityProfileType(THREAT_PREVENTION_PROFILE_TYPE),
description=description,
labels=labels,
)
return self._security_profile_client.Create(
self.messages.NetworksecurityOrganizationsLocationsSecurityProfilesCreateRequest(
parent=parent,
securityProfile=profile,
securityProfileId=sp_id,
)
)
def ListThreatPreventionProfiles(self, parent, limit=None, page_size=None):
"""Calls the ListSecurityProfiles API, filtering by type."""
return [
profile
for profile in self.ListSecurityProfiles(parent, limit, page_size)
if profile.type
== self._ParseSecurityProfileType(THREAT_PREVENTION_PROFILE_TYPE)
]

View File

@@ -0,0 +1,58 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""API wrapper for `gcloud network-security security-profiles url-filtering` commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.network_security.security_profiles import sp_api
URL_FILTERING_PROFILE_TYPE = 'URL_FILTERING'
class Client(sp_api.Client):
"""API client for URL filtering commands."""
def CreateUrlFilteringProfile(
self,
sp_id,
parent,
description,
labels,
):
"""Calls the Create Security Profile API to create a Url Filtering Profile."""
profile = self.messages.SecurityProfile(
type=self._ParseSecurityProfileType(URL_FILTERING_PROFILE_TYPE),
description=description,
labels=labels,
)
return self._security_profile_client.Create(
self.messages.NetworksecurityOrganizationsLocationsSecurityProfilesCreateRequest(
parent=parent,
securityProfile=profile,
securityProfileId=sp_id,
)
)
def ListUrlFilteringProfiles(self, parent, limit=None, page_size=None):
"""Calls the ListSecurityProfiles API, filtering by type."""
profiles = self.ListSecurityProfiles(parent, limit, page_size)
return [
profile
for profile in profiles
if profile.type
== self._ParseSecurityProfileType(URL_FILTERING_PROFILE_TYPE)
]