diff --git a/composer.json b/composer.json index c2f3e9c3be73..f7ff669e291d 100644 --- a/composer.json +++ b/composer.json @@ -57,8 +57,8 @@ "league/json-guard": "^0.3", "erusev/parsedown": "^1.6", "vierbergenlars/php-semver": "^3.0", - "google/proto-client": "^0.21.0", - "google/gax": "^0.21.0", + "google/proto-client": "^0.22.0", + "google/gax": "^0.22.1", "symfony/lock": "3.3.x-dev#1ba6ac9", "phpseclib/phpseclib": "^2" }, @@ -114,4 +114,4 @@ "entry": "ServiceBuilder.php" } } -} \ No newline at end of file +} diff --git a/src/Dlp/V2beta1/DlpServiceClient.php b/src/Dlp/V2beta1/DlpServiceClient.php index ad2c868b03de..eb844f8a804f 100644 --- a/src/Dlp/V2beta1/DlpServiceClient.php +++ b/src/Dlp/V2beta1/DlpServiceClient.php @@ -30,728 +30,12 @@ namespace Google\Cloud\Dlp\V2beta1; -use Google\GAX\AgentHeaderDescriptor; -use Google\GAX\ApiCallable; -use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; -use Google\GAX\GrpcCredentialsHelper; -use Google\GAX\LongRunning\OperationsClient; -use Google\GAX\OperationResponse; -use Google\GAX\PathTemplate; -use Google\Privacy\Dlp\V2beta1\ContentItem; -use Google\Privacy\Dlp\V2beta1\CreateInspectOperationRequest; -use Google\Privacy\Dlp\V2beta1\DlpServiceGrpcClient; -use Google\Privacy\Dlp\V2beta1\InspectConfig; -use Google\Privacy\Dlp\V2beta1\InspectContentRequest; -use Google\Privacy\Dlp\V2beta1\ListInfoTypesRequest; -use Google\Privacy\Dlp\V2beta1\ListInspectFindingsRequest; -use Google\Privacy\Dlp\V2beta1\ListRootCategoriesRequest; -use Google\Privacy\Dlp\V2beta1\OutputStorageConfig; -use Google\Privacy\Dlp\V2beta1\RedactContentRequest; -use Google\Privacy\Dlp\V2beta1\RedactContentRequest_ImageRedactionConfig as ImageRedactionConfig; -use Google\Privacy\Dlp\V2beta1\RedactContentRequest_ReplaceConfig as ReplaceConfig; -use Google\Privacy\Dlp\V2beta1\StorageConfig; +use Google\Cloud\Dlp\V2beta1\Gapic\DlpServiceGapicClient; /** - * Service Description: The DLP API is a service that allows clients - * to detect the presence of Personally Identifiable Information (PII) and other - * privacy-sensitive data in user-supplied, unstructured data streams, like text - * blocks or images. - * The service also includes methods for sensitive data redaction and - * scheduling of data scans on Google Cloud Platform based data sets. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $dlpServiceClient = new DlpServiceClient(); - * $inspectConfig = new InspectConfig(); - * $items = []; - * $response = $dlpServiceClient->inspectContent($inspectConfig, $items); - * } finally { - * $dlpServiceClient->close(); - * } - * ``` - * - * Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. - * - * @experimental + * {@inheritdoc} */ -class DlpServiceClient +class DlpServiceClient extends DlpServiceGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'dlp.googleapis.com'; - - /** - * The default port of the service. - */ - const DEFAULT_SERVICE_PORT = 443; - - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - - /** - * The name of the code generator, to be included in the agent header. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $resultNameTemplate; - - private $grpcCredentialsHelper; - private $dlpServiceStub; - private $scopes; - private $defaultCallSettings; - private $descriptors; - private $operationsClient; - - /** - * Formats a string containing the fully-qualified path to represent - * a result resource. - * - * @param string $result - * - * @return string The formatted result resource. - * @experimental - */ - public static function formatResultName($result) - { - return self::getResultNameTemplate()->render([ - 'result' => $result, - ]); - } - - /** - * Parses the result from the given fully-qualified path which - * represents a result resource. - * - * @param string $resultName The fully-qualified result resource. - * - * @return string The extracted result value. - * @experimental - */ - public static function parseResultFromResultName($resultName) - { - return self::getResultNameTemplate()->match($resultName)['result']; - } - - private static function getResultNameTemplate() - { - if (self::$resultNameTemplate == null) { - self::$resultNameTemplate = new PathTemplate('inspect/results/{result}'); - } - - return self::$resultNameTemplate; - } - - private static function getLongRunningDescriptors() - { - return [ - 'createInspectOperation' => [ - 'operationReturnType' => '\Google\Privacy\Dlp\V2beta1\InspectOperationResult', - 'metadataReturnType' => '\Google\Privacy\Dlp\V2beta1\InspectOperationMetadata', - ], - ]; - } - - private static function getGapicVersion() - { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; - } - } - - /** - * Return an OperationsClient object with the same endpoint as $this. - * - * @return \Google\GAX\LongRunning\OperationsClient - * @experimental - */ - public function getOperationsClient() - { - return $this->operationsClient; - } - - /** - * Resume an existing long running operation that was previously started - * by a long running API method. If $methodName is not provided, or does - * not match a long running API method, then the operation can still be - * resumed, but the OperationResponse object will not deserialize the - * final response. - * - * @param string $operationName The name of the long running operation - * @param string $methodName The name of the method used to start the operation - * - * @return \Google\GAX\OperationResponse - * @experimental - */ - public function resumeOperation($operationName, $methodName = null) - { - $lroDescriptors = self::getLongRunningDescriptors(); - if (!is_null($methodName) && array_key_exists($methodName, $lroDescriptors)) { - $options = $lroDescriptors[$methodName]; - } else { - $options = []; - } - $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); - $operation->reload(); - - return $operation; - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'dlp.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the DLP API. - * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - if (array_key_exists('operationsClient', $options)) { - $this->operationsClient = $options['operationsClient']; - } else { - $operationsClientOptions = $options; - unset($operationsClientOptions['timeoutMillis']); - unset($operationsClientOptions['retryingOverride']); - $this->operationsClient = new OperationsClient($operationsClientOptions); - } - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'inspectContent' => $defaultDescriptors, - 'redactContent' => $defaultDescriptors, - 'createInspectOperation' => $defaultDescriptors, - 'listInspectFindings' => $defaultDescriptors, - 'listInfoTypes' => $defaultDescriptors, - 'listRootCategories' => $defaultDescriptors, - ]; - $longRunningDescriptors = self::getLongRunningDescriptors(); - foreach ($longRunningDescriptors as $method => $longRunningDescriptor) { - $this->descriptors[$method]['longRunningDescriptor'] = $longRunningDescriptor + ['operationsClient' => $this->operationsClient]; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/dlp_service_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.privacy.dlp.v2beta1.DlpService', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createDlpServiceStubFunction = function ($hostname, $opts) { - return new DlpServiceGrpcClient($hostname, $opts); - }; - if (array_key_exists('createDlpServiceStubFunction', $options)) { - $createDlpServiceStubFunction = $options['createDlpServiceStubFunction']; - } - $this->dlpServiceStub = $this->grpcCredentialsHelper->createStub( - $createDlpServiceStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Finds potentially sensitive info in a list of strings. - * This method has limits on input size, processing time, and output size. - * - * Sample code: - * ``` - * try { - * $dlpServiceClient = new DlpServiceClient(); - * $inspectConfig = new InspectConfig(); - * $items = []; - * $response = $dlpServiceClient->inspectContent($inspectConfig, $items); - * } finally { - * $dlpServiceClient->close(); - * } - * ``` - * - * @param InspectConfig $inspectConfig Configuration for the inspector. - * @param ContentItem[] $items The list of items to inspect. Items in a single request are - * considered "related" unless inspect_config.independent_inputs is true. - * Up to 100 are allowed per request. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Privacy\Dlp\V2beta1\InspectContentResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function inspectContent($inspectConfig, $items, $optionalArgs = []) - { - $request = new InspectContentRequest(); - $request->setInspectConfig($inspectConfig); - $request->setItems($items); - - $mergedSettings = $this->defaultCallSettings['inspectContent']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->dlpServiceStub, - 'InspectContent', - $mergedSettings, - $this->descriptors['inspectContent'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Redacts potentially sensitive info from a list of strings. - * This method has limits on input size, processing time, and output size. - * - * Sample code: - * ``` - * try { - * $dlpServiceClient = new DlpServiceClient(); - * $inspectConfig = new InspectConfig(); - * $items = []; - * $replaceConfigs = []; - * $response = $dlpServiceClient->redactContent($inspectConfig, $items, $replaceConfigs); - * } finally { - * $dlpServiceClient->close(); - * } - * ``` - * - * @param InspectConfig $inspectConfig Configuration for the inspector. - * @param ContentItem[] $items The list of items to inspect. Up to 100 are allowed per request. - * @param ReplaceConfig[] $replaceConfigs The strings to replace findings text findings with. Must specify at least - * one of these or one ImageRedactionConfig if redacting images. - * @param array $optionalArgs { - * Optional. - * - * @type ImageRedactionConfig[] $imageRedactionConfigs - * The configuration for specifying what content to redact from images. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Privacy\Dlp\V2beta1\RedactContentResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function redactContent($inspectConfig, $items, $replaceConfigs, $optionalArgs = []) - { - $request = new RedactContentRequest(); - $request->setInspectConfig($inspectConfig); - $request->setItems($items); - $request->setReplaceConfigs($replaceConfigs); - if (isset($optionalArgs['imageRedactionConfigs'])) { - $request->setImageRedactionConfigs($optionalArgs['imageRedactionConfigs']); - } - - $mergedSettings = $this->defaultCallSettings['redactContent']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->dlpServiceStub, - 'RedactContent', - $mergedSettings, - $this->descriptors['redactContent'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Schedules a job scanning content in a Google Cloud Platform data - * repository. - * - * Sample code: - * ``` - * try { - * $dlpServiceClient = new DlpServiceClient(); - * $inspectConfig = new InspectConfig(); - * $storageConfig = new StorageConfig(); - * $outputConfig = new OutputStorageConfig(); - * $operationResponse = $dlpServiceClient->createInspectOperation($inspectConfig, $storageConfig, $outputConfig); - * $operationResponse->pollUntilComplete(); - * if ($operationResponse->operationSucceeded()) { - * $result = $operationResponse->getResult(); - * // doSomethingWith($result) - * } else { - * $error = $operationResponse->getError(); - * // handleError($error) - * } - * - * // OR start the operation, keep the operation name, and resume later - * $operationResponse = $dlpServiceClient->createInspectOperation($inspectConfig, $storageConfig, $outputConfig); - * $operationName = $operationResponse->getName(); - * // ... do other work - * $newOperationResponse = $dlpServiceClient->resumeOperation($operationName, 'createInspectOperation'); - * while (!$newOperationResponse->isDone()) { - * // ... do other work - * $newOperationResponse->reload(); - * } - * if ($newOperationResponse->operationSucceeded()) { - * $result = $newOperationResponse->getResult(); - * // doSomethingWith($result) - * } else { - * $error = $newOperationResponse->getError(); - * // handleError($error) - * } - * } finally { - * $dlpServiceClient->close(); - * } - * ``` - * - * @param InspectConfig $inspectConfig Configuration for the inspector. - * @param StorageConfig $storageConfig Specification of the data set to process. - * @param OutputStorageConfig $outputConfig Optional location to store findings. The bucket must already exist and - * the Google APIs service account for DLP must have write permission to - * write to the given bucket. - *
Results are split over multiple csv files with each file name matching - * the pattern "[operation_id]_[count].csv", for example - * `3094877188788974909_1.csv`. The `operation_id` matches the - * identifier for the Operation, and the `count` is a counter used for - * tracking the number of files written.
The CSV file(s) contain the - * following columns regardless of storage type scanned:
For Cloud Storage the next columns are:
For Cloud Datastore the next columns are:
Examples:
- *
Results are split over multiple csv files with each file name matching + * the pattern "[operation_id]_[count].csv", for example + * `3094877188788974909_1.csv`. The `operation_id` matches the + * identifier for the Operation, and the `count` is a counter used for + * tracking the number of files written.
The CSV file(s) contain the + * following columns regardless of storage type scanned:
For Cloud Storage the next columns are:
For Cloud Datastore the next columns are:
For BigQuery the next columns are:
Examples:
+ *
projects/projectID/groups/group_name.
- * Call
- *
- * groupStats.list to return a list of groups belonging to
- * this project.
- *
- * Example: projects/my-project-123/groups/my-group
- * @param array $optionalArgs {
- * Optional.
- *
- * @type \Google\GAX\RetrySettings $retrySettings
- * Retry settings to use for this call. If present, then
- * $timeoutMillis is ignored.
- * @type int $timeoutMillis
- * Timeout to use for this call. Only used if $retrySettings
- * is not set.
- * }
- *
- * @return \Google\Devtools\Clouderrorreporting\V1beta1\ErrorGroup
- *
- * @throws \Google\GAX\ApiException if the remote call fails
- * @experimental
- */
- public function getGroup($groupName, $optionalArgs = [])
- {
- $request = new GetGroupRequest();
- $request->setGroupName($groupName);
-
- $mergedSettings = $this->defaultCallSettings['getGroup']->merge(
- new CallSettings($optionalArgs)
- );
- $callable = ApiCallable::createApiCall(
- $this->errorGroupServiceStub,
- 'GetGroup',
- $mergedSettings,
- $this->descriptors['getGroup']
- );
-
- return $callable(
- $request,
- [],
- ['call_credentials_callback' => $this->createCredentialsCallback()]);
- }
-
- /**
- * Replace the data for the specified group.
- * Fails if the group does not exist.
- *
- * Sample code:
- * ```
- * try {
- * $errorGroupServiceClient = new ErrorGroupServiceClient();
- * $group = new ErrorGroup();
- * $response = $errorGroupServiceClient->updateGroup($group);
- * } finally {
- * $errorGroupServiceClient->close();
- * }
- * ```
- *
- * @param ErrorGroup $group [Required] The group which replaces the resource on the server.
- * @param array $optionalArgs {
- * Optional.
- *
- * @type \Google\GAX\RetrySettings $retrySettings
- * Retry settings to use for this call. If present, then
- * $timeoutMillis is ignored.
- * @type int $timeoutMillis
- * Timeout to use for this call. Only used if $retrySettings
- * is not set.
- * }
- *
- * @return \Google\Devtools\Clouderrorreporting\V1beta1\ErrorGroup
- *
- * @throws \Google\GAX\ApiException if the remote call fails
- * @experimental
- */
- public function updateGroup($group, $optionalArgs = [])
- {
- $request = new UpdateGroupRequest();
- $request->setGroup($group);
-
- $mergedSettings = $this->defaultCallSettings['updateGroup']->merge(
- new CallSettings($optionalArgs)
- );
- $callable = ApiCallable::createApiCall(
- $this->errorGroupServiceStub,
- 'UpdateGroup',
- $mergedSettings,
- $this->descriptors['updateGroup']
- );
-
- return $callable(
- $request,
- [],
- ['call_credentials_callback' => $this->createCredentialsCallback()]);
- }
-
- /**
- * Initiates an orderly shutdown in which preexisting calls continue but new
- * calls are immediately cancelled.
- *
- * @experimental
- */
- public function close()
- {
- $this->errorGroupServiceStub->close();
- }
-
- private function createCredentialsCallback()
- {
- return $this->grpcCredentialsHelper->createCallCredentialsCallback();
- }
+ // This class is intentionally empty, and is intended to hold manual additions to the generated {@see ErrorGroupServiceClientImpl} class.
}
diff --git a/src/ErrorReporting/V1beta1/ErrorStatsServiceClient.php b/src/ErrorReporting/V1beta1/ErrorStatsServiceClient.php
index c52614274088..8cf915ee7f17 100644
--- a/src/ErrorReporting/V1beta1/ErrorStatsServiceClient.php
+++ b/src/ErrorReporting/V1beta1/ErrorStatsServiceClient.php
@@ -30,576 +30,12 @@
namespace Google\Cloud\ErrorReporting\V1beta1;
-use Google\Devtools\Clouderrorreporting\V1beta1\DeleteEventsRequest;
-use Google\Devtools\Clouderrorreporting\V1beta1\ErrorStatsServiceGrpcClient;
-use Google\Devtools\Clouderrorreporting\V1beta1\ListEventsRequest;
-use Google\Devtools\Clouderrorreporting\V1beta1\ListGroupStatsRequest;
-use Google\Devtools\Clouderrorreporting\V1beta1\QueryTimeRange;
-use Google\Devtools\Clouderrorreporting\V1beta1\ServiceContextFilter;
-use Google\GAX\AgentHeaderDescriptor;
-use Google\GAX\ApiCallable;
-use Google\GAX\CallSettings;
-use Google\GAX\GrpcConstants;
-use Google\GAX\GrpcCredentialsHelper;
-use Google\GAX\PageStreamingDescriptor;
-use Google\GAX\PathTemplate;
-use Google\Protobuf\Duration;
-use Google\Protobuf\Timestamp;
+use Google\Cloud\ErrorReporting\V1beta1\Gapic\ErrorStatsServiceGapicClient;
/**
- * Service Description: An API for retrieving and managing error statistics as well as data for
- * individual events.
- *
- * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change
- * more frequently than those which have been declared beta or 1.0, including changes which break
- * backwards compatibility.
- *
- * This class provides the ability to make remote calls to the backing service through method
- * calls that map to API methods. Sample code to get started:
- *
- * ```
- * try {
- * $errorStatsServiceClient = new ErrorStatsServiceClient();
- * $formattedProjectName = ErrorStatsServiceClient::formatProjectName("[PROJECT]");
- * $timeRange = new QueryTimeRange();
- * // Iterate through all elements
- * $pagedResponse = $errorStatsServiceClient->listGroupStats($formattedProjectName, $timeRange);
- * foreach ($pagedResponse->iterateAllElements() as $element) {
- * // doSomethingWith($element);
- * }
- *
- * // OR iterate over pages of elements, with the maximum page size set to 5
- * $pagedResponse = $errorStatsServiceClient->listGroupStats($formattedProjectName, $timeRange, ['pageSize' => 5]);
- * foreach ($pagedResponse->iteratePages() as $page) {
- * foreach ($page as $element) {
- * // doSomethingWith($element);
- * }
- * }
- * } finally {
- * $errorStatsServiceClient->close();
- * }
- * ```
- *
- * Many parameters require resource names to be formatted in a particular way. To assist
- * with these names, this class includes a format method for each type of name, and additionally
- * a parse method to extract the individual identifiers contained within names that are
- * returned.
- *
- * @experimental
+ * {@inheritdoc}
*/
-class ErrorStatsServiceClient
+class ErrorStatsServiceClient extends ErrorStatsServiceGapicClient
{
- /**
- * The default address of the service.
- */
- const SERVICE_ADDRESS = 'clouderrorreporting.googleapis.com';
-
- /**
- * The default port of the service.
- */
- const DEFAULT_SERVICE_PORT = 443;
-
- /**
- * The default timeout for non-retrying methods.
- */
- const DEFAULT_TIMEOUT_MILLIS = 30000;
-
- /**
- * The name of the code generator, to be included in the agent header.
- */
- const CODEGEN_NAME = 'gapic';
-
- /**
- * The code generator version, to be included in the agent header.
- */
- const CODEGEN_VERSION = '0.0.5';
-
- private static $projectNameTemplate;
-
- private $grpcCredentialsHelper;
- private $errorStatsServiceStub;
- private $scopes;
- private $defaultCallSettings;
- private $descriptors;
-
- /**
- * Formats a string containing the fully-qualified path to represent
- * a project resource.
- *
- * @param string $project
- *
- * @return string The formatted project resource.
- * @experimental
- */
- public static function formatProjectName($project)
- {
- return self::getProjectNameTemplate()->render([
- 'project' => $project,
- ]);
- }
-
- /**
- * Parses the project from the given fully-qualified path which
- * represents a project resource.
- *
- * @param string $projectName The fully-qualified project resource.
- *
- * @return string The extracted project value.
- * @experimental
- */
- public static function parseProjectFromProjectName($projectName)
- {
- return self::getProjectNameTemplate()->match($projectName)['project'];
- }
-
- private static function getProjectNameTemplate()
- {
- if (self::$projectNameTemplate == null) {
- self::$projectNameTemplate = new PathTemplate('projects/{project}');
- }
-
- return self::$projectNameTemplate;
- }
-
- private static function getPageStreamingDescriptors()
- {
- $listGroupStatsPageStreamingDescriptor =
- new PageStreamingDescriptor([
- 'requestPageTokenGetMethod' => 'getPageToken',
- 'requestPageTokenSetMethod' => 'setPageToken',
- 'requestPageSizeGetMethod' => 'getPageSize',
- 'requestPageSizeSetMethod' => 'setPageSize',
- 'responsePageTokenGetMethod' => 'getNextPageToken',
- 'resourcesGetMethod' => 'getErrorGroupStats',
- ]);
- $listEventsPageStreamingDescriptor =
- new PageStreamingDescriptor([
- 'requestPageTokenGetMethod' => 'getPageToken',
- 'requestPageTokenSetMethod' => 'setPageToken',
- 'requestPageSizeGetMethod' => 'getPageSize',
- 'requestPageSizeSetMethod' => 'setPageSize',
- 'responsePageTokenGetMethod' => 'getNextPageToken',
- 'resourcesGetMethod' => 'getErrorEvents',
- ]);
-
- $pageStreamingDescriptors = [
- 'listGroupStats' => $listGroupStatsPageStreamingDescriptor,
- 'listEvents' => $listEventsPageStreamingDescriptor,
- ];
-
- return $pageStreamingDescriptors;
- }
-
- private static function getGapicVersion()
- {
- if (file_exists(__DIR__.'/../VERSION')) {
- return trim(file_get_contents(__DIR__.'/../VERSION'));
- } elseif (class_exists('\Google\Cloud\ServiceBuilder')) {
- return \Google\Cloud\ServiceBuilder::VERSION;
- } else {
- return;
- }
- }
-
- // TODO(garrettjones): add channel (when supported in gRPC)
- /**
- * Constructor.
- *
- * @param array $options {
- * Optional. Options for configuring the service API wrapper.
- *
- * @type string $serviceAddress The domain name of the API remote host.
- * Default 'clouderrorreporting.googleapis.com'.
- * @type mixed $port The port on which to connect to the remote host. Default 443.
- * @type \Grpc\ChannelCredentials $sslCreds
- * A `ChannelCredentials` for use with an SSL-enabled channel.
- * Default: a credentials object returned from
- * \Grpc\ChannelCredentials::createSsl()
- * @type array $scopes A string array of scopes to use when acquiring credentials.
- * Default the scopes for the Stackdriver Error Reporting API.
- * @type array $retryingOverride
- * An associative array of string => RetryOptions, where the keys
- * are method names (e.g. 'createFoo'), that overrides default retrying
- * settings. A value of null indicates that the method in question should
- * not retry.
- * @type int $timeoutMillis The timeout in milliseconds to use for calls
- * that don't use retries. For calls that use retries,
- * set the timeout in RetryOptions.
- * Default: 30000 (30 seconds)
- * @type \Google\Auth\CredentialsLoader $credentialsLoader
- * A CredentialsLoader object created using the
- * Google\Auth library.
- * }
- * @experimental
- */
- public function __construct($options = [])
- {
- $defaultOptions = [
- 'serviceAddress' => self::SERVICE_ADDRESS,
- 'port' => self::DEFAULT_SERVICE_PORT,
- 'scopes' => [
- 'https://www.googleapis.com/auth/cloud-platform',
- ],
- 'retryingOverride' => null,
- 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS,
- 'libName' => null,
- 'libVersion' => null,
- ];
- $options = array_merge($defaultOptions, $options);
-
- $gapicVersion = $options['libVersion'] ?: self::getGapicVersion();
-
- $headerDescriptor = new AgentHeaderDescriptor([
- 'libName' => $options['libName'],
- 'libVersion' => $options['libVersion'],
- 'gapicVersion' => $gapicVersion,
- ]);
-
- $defaultDescriptors = ['headerDescriptor' => $headerDescriptor];
- $this->descriptors = [
- 'listGroupStats' => $defaultDescriptors,
- 'listEvents' => $defaultDescriptors,
- 'deleteEvents' => $defaultDescriptors,
- ];
- $pageStreamingDescriptors = self::getPageStreamingDescriptors();
- foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) {
- $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor;
- }
-
- $clientConfigJsonString = file_get_contents(__DIR__.'/resources/error_stats_service_client_config.json');
- $clientConfig = json_decode($clientConfigJsonString, true);
- $this->defaultCallSettings =
- CallSettings::load(
- 'google.devtools.clouderrorreporting.v1beta1.ErrorStatsService',
- $clientConfig,
- $options['retryingOverride'],
- GrpcConstants::getStatusCodeNames(),
- $options['timeoutMillis']
- );
-
- $this->scopes = $options['scopes'];
-
- $createStubOptions = [];
- if (array_key_exists('sslCreds', $options)) {
- $createStubOptions['sslCreds'] = $options['sslCreds'];
- }
- $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions);
- $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions);
-
- $createErrorStatsServiceStubFunction = function ($hostname, $opts) {
- return new ErrorStatsServiceGrpcClient($hostname, $opts);
- };
- if (array_key_exists('createErrorStatsServiceStubFunction', $options)) {
- $createErrorStatsServiceStubFunction = $options['createErrorStatsServiceStubFunction'];
- }
- $this->errorStatsServiceStub = $this->grpcCredentialsHelper->createStub(
- $createErrorStatsServiceStubFunction,
- $options['serviceAddress'],
- $options['port'],
- $createStubOptions
- );
- }
-
- /**
- * Lists the specified groups.
- *
- * Sample code:
- * ```
- * try {
- * $errorStatsServiceClient = new ErrorStatsServiceClient();
- * $formattedProjectName = ErrorStatsServiceClient::formatProjectName("[PROJECT]");
- * $timeRange = new QueryTimeRange();
- * // Iterate through all elements
- * $pagedResponse = $errorStatsServiceClient->listGroupStats($formattedProjectName, $timeRange);
- * foreach ($pagedResponse->iterateAllElements() as $element) {
- * // doSomethingWith($element);
- * }
- *
- * // OR iterate over pages of elements, with the maximum page size set to 5
- * $pagedResponse = $errorStatsServiceClient->listGroupStats($formattedProjectName, $timeRange, ['pageSize' => 5]);
- * foreach ($pagedResponse->iteratePages() as $page) {
- * foreach ($page as $element) {
- * // doSomethingWith($element);
- * }
- * }
- * } finally {
- * $errorStatsServiceClient->close();
- * }
- * ```
- *
- * @param string $projectName [Required] The resource name of the Google Cloud Platform project. Written
- * as projects/ plus the
- * Google Cloud
- * Platform project ID.
- *
- * Example: projects/my-project-123.
- * @param QueryTimeRange $timeRange [Optional] List data for the given time range.
- * If not set a default time range is used. The field time_range_begin
- * in the response will specify the beginning of this time range.
- * Only ErrorGroupStats with a non-zero count in the given time
- * range are returned, unless the request contains an explicit group_id list.
- * If a group_id list is given, also ErrorGroupStats with zero
- * occurrences are returned.
- * @param array $optionalArgs {
- * Optional.
- *
- * @type string[] $groupId
- * [Optional] List all ErrorGroupStats with these IDs.
- * @type ServiceContextFilter $serviceFilter
- * [Optional] List only ErrorGroupStats which belong to a service
- * context that matches the filter.
- * Data for all service contexts is returned if this field is not specified.
- * @type Duration $timedCountDuration
- * [Optional] The preferred duration for a single returned `TimedCount`.
- * If not set, no timed counts are returned.
- * @type int $alignment
- * [Optional] The alignment of the timed counts to be returned.
- * Default is `ALIGNMENT_EQUAL_AT_END`.
- * For allowed values, use constants defined on {@see \Google\Devtools\Clouderrorreporting\V1beta1\TimedCountAlignment}
- * @type Timestamp $alignmentTime
- * [Optional] Time where the timed counts shall be aligned if rounded
- * alignment is chosen. Default is 00:00 UTC.
- * @type int $order
- * [Optional] The sort order in which the results are returned.
- * Default is `COUNT_DESC`.
- * For allowed values, use constants defined on {@see \Google\Devtools\Clouderrorreporting\V1beta1\ErrorGroupOrder}
- * @type int $pageSize
- * The maximum number of resources contained in the underlying API
- * response. The API may return fewer values in a page, even if
- * there are additional values to be retrieved.
- * @type string $pageToken
- * A page token is used to specify a page of values to be returned.
- * If no page token is specified (the default), the first page
- * of values will be returned. Any page token used here must have
- * been generated by a previous call to the API.
- * @type \Google\GAX\RetrySettings $retrySettings
- * Retry settings to use for this call. If present, then
- * $timeoutMillis is ignored.
- * @type int $timeoutMillis
- * Timeout to use for this call. Only used if $retrySettings
- * is not set.
- * }
- *
- * @return \Google\GAX\PagedListResponse
- *
- * @throws \Google\GAX\ApiException if the remote call fails
- * @experimental
- */
- public function listGroupStats($projectName, $timeRange, $optionalArgs = [])
- {
- $request = new ListGroupStatsRequest();
- $request->setProjectName($projectName);
- $request->setTimeRange($timeRange);
- if (isset($optionalArgs['groupId'])) {
- $request->setGroupId($optionalArgs['groupId']);
- }
- if (isset($optionalArgs['serviceFilter'])) {
- $request->setServiceFilter($optionalArgs['serviceFilter']);
- }
- if (isset($optionalArgs['timedCountDuration'])) {
- $request->setTimedCountDuration($optionalArgs['timedCountDuration']);
- }
- if (isset($optionalArgs['alignment'])) {
- $request->setAlignment($optionalArgs['alignment']);
- }
- if (isset($optionalArgs['alignmentTime'])) {
- $request->setAlignmentTime($optionalArgs['alignmentTime']);
- }
- if (isset($optionalArgs['order'])) {
- $request->setOrder($optionalArgs['order']);
- }
- if (isset($optionalArgs['pageSize'])) {
- $request->setPageSize($optionalArgs['pageSize']);
- }
- if (isset($optionalArgs['pageToken'])) {
- $request->setPageToken($optionalArgs['pageToken']);
- }
-
- $mergedSettings = $this->defaultCallSettings['listGroupStats']->merge(
- new CallSettings($optionalArgs)
- );
- $callable = ApiCallable::createApiCall(
- $this->errorStatsServiceStub,
- 'ListGroupStats',
- $mergedSettings,
- $this->descriptors['listGroupStats']
- );
-
- return $callable(
- $request,
- [],
- ['call_credentials_callback' => $this->createCredentialsCallback()]);
- }
-
- /**
- * Lists the specified events.
- *
- * Sample code:
- * ```
- * try {
- * $errorStatsServiceClient = new ErrorStatsServiceClient();
- * $formattedProjectName = ErrorStatsServiceClient::formatProjectName("[PROJECT]");
- * $groupId = "";
- * // Iterate through all elements
- * $pagedResponse = $errorStatsServiceClient->listEvents($formattedProjectName, $groupId);
- * foreach ($pagedResponse->iterateAllElements() as $element) {
- * // doSomethingWith($element);
- * }
- *
- * // OR iterate over pages of elements, with the maximum page size set to 5
- * $pagedResponse = $errorStatsServiceClient->listEvents($formattedProjectName, $groupId, ['pageSize' => 5]);
- * foreach ($pagedResponse->iteratePages() as $page) {
- * foreach ($page as $element) {
- * // doSomethingWith($element);
- * }
- * }
- * } finally {
- * $errorStatsServiceClient->close();
- * }
- * ```
- *
- * @param string $projectName [Required] The resource name of the Google Cloud Platform project. Written
- * as `projects/` plus the
- * [Google Cloud Platform project
- * ID](https://support.google.com/cloud/answer/6158840).
- * Example: `projects/my-project-123`.
- * @param string $groupId [Required] The group for which events shall be returned.
- * @param array $optionalArgs {
- * Optional.
- *
- * @type ServiceContextFilter $serviceFilter
- * [Optional] List only ErrorGroups which belong to a service context that
- * matches the filter.
- * Data for all service contexts is returned if this field is not specified.
- * @type QueryTimeRange $timeRange
- * [Optional] List only data for the given time range.
- * If not set a default time range is used. The field time_range_begin
- * in the response will specify the beginning of this time range.
- * @type int $pageSize
- * The maximum number of resources contained in the underlying API
- * response. The API may return fewer values in a page, even if
- * there are additional values to be retrieved.
- * @type string $pageToken
- * A page token is used to specify a page of values to be returned.
- * If no page token is specified (the default), the first page
- * of values will be returned. Any page token used here must have
- * been generated by a previous call to the API.
- * @type \Google\GAX\RetrySettings $retrySettings
- * Retry settings to use for this call. If present, then
- * $timeoutMillis is ignored.
- * @type int $timeoutMillis
- * Timeout to use for this call. Only used if $retrySettings
- * is not set.
- * }
- *
- * @return \Google\GAX\PagedListResponse
- *
- * @throws \Google\GAX\ApiException if the remote call fails
- * @experimental
- */
- public function listEvents($projectName, $groupId, $optionalArgs = [])
- {
- $request = new ListEventsRequest();
- $request->setProjectName($projectName);
- $request->setGroupId($groupId);
- if (isset($optionalArgs['serviceFilter'])) {
- $request->setServiceFilter($optionalArgs['serviceFilter']);
- }
- if (isset($optionalArgs['timeRange'])) {
- $request->setTimeRange($optionalArgs['timeRange']);
- }
- if (isset($optionalArgs['pageSize'])) {
- $request->setPageSize($optionalArgs['pageSize']);
- }
- if (isset($optionalArgs['pageToken'])) {
- $request->setPageToken($optionalArgs['pageToken']);
- }
-
- $mergedSettings = $this->defaultCallSettings['listEvents']->merge(
- new CallSettings($optionalArgs)
- );
- $callable = ApiCallable::createApiCall(
- $this->errorStatsServiceStub,
- 'ListEvents',
- $mergedSettings,
- $this->descriptors['listEvents']
- );
-
- return $callable(
- $request,
- [],
- ['call_credentials_callback' => $this->createCredentialsCallback()]);
- }
-
- /**
- * Deletes all error events of a given project.
- *
- * Sample code:
- * ```
- * try {
- * $errorStatsServiceClient = new ErrorStatsServiceClient();
- * $formattedProjectName = ErrorStatsServiceClient::formatProjectName("[PROJECT]");
- * $response = $errorStatsServiceClient->deleteEvents($formattedProjectName);
- * } finally {
- * $errorStatsServiceClient->close();
- * }
- * ```
- *
- * @param string $projectName [Required] The resource name of the Google Cloud Platform project. Written
- * as `projects/` plus the
- * [Google Cloud Platform project
- * ID](https://support.google.com/cloud/answer/6158840).
- * Example: `projects/my-project-123`.
- * @param array $optionalArgs {
- * Optional.
- *
- * @type \Google\GAX\RetrySettings $retrySettings
- * Retry settings to use for this call. If present, then
- * $timeoutMillis is ignored.
- * @type int $timeoutMillis
- * Timeout to use for this call. Only used if $retrySettings
- * is not set.
- * }
- *
- * @return \Google\Devtools\Clouderrorreporting\V1beta1\DeleteEventsResponse
- *
- * @throws \Google\GAX\ApiException if the remote call fails
- * @experimental
- */
- public function deleteEvents($projectName, $optionalArgs = [])
- {
- $request = new DeleteEventsRequest();
- $request->setProjectName($projectName);
-
- $mergedSettings = $this->defaultCallSettings['deleteEvents']->merge(
- new CallSettings($optionalArgs)
- );
- $callable = ApiCallable::createApiCall(
- $this->errorStatsServiceStub,
- 'DeleteEvents',
- $mergedSettings,
- $this->descriptors['deleteEvents']
- );
-
- return $callable(
- $request,
- [],
- ['call_credentials_callback' => $this->createCredentialsCallback()]);
- }
-
- /**
- * Initiates an orderly shutdown in which preexisting calls continue but new
- * calls are immediately cancelled.
- *
- * @experimental
- */
- public function close()
- {
- $this->errorStatsServiceStub->close();
- }
-
- private function createCredentialsCallback()
- {
- return $this->grpcCredentialsHelper->createCallCredentialsCallback();
- }
+ // This class is intentionally empty, and is intended to hold manual additions to the generated {@see ErrorStatsServiceClientImpl} class.
}
diff --git a/src/ErrorReporting/V1beta1/Gapic/ErrorGroupServiceGapicClient.php b/src/ErrorReporting/V1beta1/Gapic/ErrorGroupServiceGapicClient.php
new file mode 100644
index 000000000000..a024985cdbc5
--- /dev/null
+++ b/src/ErrorReporting/V1beta1/Gapic/ErrorGroupServiceGapicClient.php
@@ -0,0 +1,392 @@
+getGroup($formattedGroupName);
+ * } finally {
+ * $errorGroupServiceClient->close();
+ * }
+ * ```
+ *
+ * Many parameters require resource names to be formatted in a particular way. To assist
+ * with these names, this class includes a format method for each type of name, and additionally
+ * a parse method to extract the individual identifiers contained within names that are
+ * returned.
+ *
+ * @experimental
+ */
+class ErrorGroupServiceGapicClient
+{
+ /**
+ * The default address of the service.
+ */
+ const SERVICE_ADDRESS = 'clouderrorreporting.googleapis.com';
+
+ /**
+ * The default port of the service.
+ */
+ const DEFAULT_SERVICE_PORT = 443;
+
+ /**
+ * The default timeout for non-retrying methods.
+ */
+ const DEFAULT_TIMEOUT_MILLIS = 30000;
+
+ /**
+ * The name of the code generator, to be included in the agent header.
+ */
+ const CODEGEN_NAME = 'gapic';
+
+ /**
+ * The code generator version, to be included in the agent header.
+ */
+ const CODEGEN_VERSION = '0.0.5';
+
+ private static $groupNameTemplate;
+
+ protected $grpcCredentialsHelper;
+ protected $errorGroupServiceStub;
+ private $scopes;
+ private $defaultCallSettings;
+ private $descriptors;
+
+ /**
+ * Formats a string containing the fully-qualified path to represent
+ * a group resource.
+ *
+ * @param string $project
+ * @param string $group
+ *
+ * @return string The formatted group resource.
+ * @experimental
+ */
+ public static function formatGroupName($project, $group)
+ {
+ return self::getGroupNameTemplate()->render([
+ 'project' => $project,
+ 'group' => $group,
+ ]);
+ }
+
+ /**
+ * Parses the project from the given fully-qualified path which
+ * represents a group resource.
+ *
+ * @param string $groupName The fully-qualified group resource.
+ *
+ * @return string The extracted project value.
+ * @experimental
+ */
+ public static function parseProjectFromGroupName($groupName)
+ {
+ return self::getGroupNameTemplate()->match($groupName)['project'];
+ }
+
+ /**
+ * Parses the group from the given fully-qualified path which
+ * represents a group resource.
+ *
+ * @param string $groupName The fully-qualified group resource.
+ *
+ * @return string The extracted group value.
+ * @experimental
+ */
+ public static function parseGroupFromGroupName($groupName)
+ {
+ return self::getGroupNameTemplate()->match($groupName)['group'];
+ }
+
+ private static function getGroupNameTemplate()
+ {
+ if (self::$groupNameTemplate == null) {
+ self::$groupNameTemplate = new PathTemplate('projects/{project}/groups/{group}');
+ }
+
+ return self::$groupNameTemplate;
+ }
+
+ private static function getGapicVersion()
+ {
+ if (file_exists(__DIR__.'/../VERSION')) {
+ return trim(file_get_contents(__DIR__.'/../VERSION'));
+ } elseif (class_exists('\Google\Cloud\ServiceBuilder')) {
+ return \Google\Cloud\ServiceBuilder::VERSION;
+ } else {
+ return;
+ }
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param array $options {
+ * Optional. Options for configuring the service API wrapper.
+ *
+ * @type string $serviceAddress The domain name of the API remote host.
+ * Default 'clouderrorreporting.googleapis.com'.
+ * @type mixed $port The port on which to connect to the remote host. Default 443.
+ * @type \Grpc\Channel $channel
+ * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed.
+ * @type \Grpc\ChannelCredentials $sslCreds
+ * A `ChannelCredentials` object for use with an SSL-enabled channel.
+ * Default: a credentials object returned from
+ * \Grpc\ChannelCredentials::createSsl()
+ * NOTE: if the $channel optional argument is specified, then this argument is unused.
+ * @type bool $forceNewChannel
+ * If true, this forces gRPC to create a new channel instead of using a persistent channel.
+ * Defaults to false.
+ * NOTE: if the $channel optional argument is specified, then this option is unused.
+ * @type \Google\Auth\CredentialsLoader $credentialsLoader
+ * A CredentialsLoader object created using the Google\Auth library.
+ * @type array $scopes A string array of scopes to use when acquiring credentials.
+ * Defaults to the scopes for the Stackdriver Error Reporting API.
+ * @type array $retryingOverride
+ * An associative array of string => RetryOptions, where the keys
+ * are method names (e.g. 'createFoo'), that overrides default retrying
+ * settings. A value of null indicates that the method in question should
+ * not retry.
+ * @type int $timeoutMillis The timeout in milliseconds to use for calls
+ * that don't use retries. For calls that use retries,
+ * set the timeout in RetryOptions.
+ * Default: 30000 (30 seconds)
+ * }
+ * @experimental
+ */
+ public function __construct($options = [])
+ {
+ $defaultOptions = [
+ 'serviceAddress' => self::SERVICE_ADDRESS,
+ 'port' => self::DEFAULT_SERVICE_PORT,
+ 'scopes' => [
+ 'https://www.googleapis.com/auth/cloud-platform',
+ ],
+ 'retryingOverride' => null,
+ 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS,
+ 'libName' => null,
+ 'libVersion' => null,
+ ];
+ $options = array_merge($defaultOptions, $options);
+
+ $gapicVersion = $options['libVersion'] ?: self::getGapicVersion();
+
+ $headerDescriptor = new AgentHeaderDescriptor([
+ 'libName' => $options['libName'],
+ 'libVersion' => $options['libVersion'],
+ 'gapicVersion' => $gapicVersion,
+ ]);
+
+ $defaultDescriptors = ['headerDescriptor' => $headerDescriptor];
+ $this->descriptors = [
+ 'getGroup' => $defaultDescriptors,
+ 'updateGroup' => $defaultDescriptors,
+ ];
+
+ $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/error_group_service_client_config.json');
+ $clientConfig = json_decode($clientConfigJsonString, true);
+ $this->defaultCallSettings =
+ CallSettings::load(
+ 'google.devtools.clouderrorreporting.v1beta1.ErrorGroupService',
+ $clientConfig,
+ $options['retryingOverride'],
+ GrpcConstants::getStatusCodeNames(),
+ $options['timeoutMillis']
+ );
+
+ $this->scopes = $options['scopes'];
+
+ $createStubOptions = [];
+ if (array_key_exists('sslCreds', $options)) {
+ $createStubOptions['sslCreds'] = $options['sslCreds'];
+ }
+ $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options);
+
+ $createErrorGroupServiceStubFunction = function ($hostname, $opts, $channel) {
+ return new ErrorGroupServiceGrpcClient($hostname, $opts, $channel);
+ };
+ if (array_key_exists('createErrorGroupServiceStubFunction', $options)) {
+ $createErrorGroupServiceStubFunction = $options['createErrorGroupServiceStubFunction'];
+ }
+ $this->errorGroupServiceStub = $this->grpcCredentialsHelper->createStub($createErrorGroupServiceStubFunction);
+ }
+
+ /**
+ * Get the specified group.
+ *
+ * Sample code:
+ * ```
+ * try {
+ * $errorGroupServiceClient = new ErrorGroupServiceClient();
+ * $formattedGroupName = ErrorGroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]");
+ * $response = $errorGroupServiceClient->getGroup($formattedGroupName);
+ * } finally {
+ * $errorGroupServiceClient->close();
+ * }
+ * ```
+ *
+ * @param string $groupName [Required] The group resource name. Written as
+ * projects/projectID/groups/group_name.
+ * Call
+ *
+ * groupStats.list to return a list of groups belonging to
+ * this project.
+ *
+ * Example: projects/my-project-123/groups/my-group
+ * @param array $optionalArgs {
+ * Optional.
+ *
+ * @type \Google\GAX\RetrySettings $retrySettings
+ * Retry settings to use for this call. If present, then
+ * $timeoutMillis is ignored.
+ * @type int $timeoutMillis
+ * Timeout to use for this call. Only used if $retrySettings
+ * is not set.
+ * }
+ *
+ * @return \Google\Devtools\Clouderrorreporting\V1beta1\ErrorGroup
+ *
+ * @throws \Google\GAX\ApiException if the remote call fails
+ * @experimental
+ */
+ public function getGroup($groupName, $optionalArgs = [])
+ {
+ $request = new GetGroupRequest();
+ $request->setGroupName($groupName);
+
+ $mergedSettings = $this->defaultCallSettings['getGroup']->merge(
+ new CallSettings($optionalArgs)
+ );
+ $callable = ApiCallable::createApiCall(
+ $this->errorGroupServiceStub,
+ 'GetGroup',
+ $mergedSettings,
+ $this->descriptors['getGroup']
+ );
+
+ return $callable(
+ $request,
+ [],
+ ['call_credentials_callback' => $this->createCredentialsCallback()]);
+ }
+
+ /**
+ * Replace the data for the specified group.
+ * Fails if the group does not exist.
+ *
+ * Sample code:
+ * ```
+ * try {
+ * $errorGroupServiceClient = new ErrorGroupServiceClient();
+ * $group = new ErrorGroup();
+ * $response = $errorGroupServiceClient->updateGroup($group);
+ * } finally {
+ * $errorGroupServiceClient->close();
+ * }
+ * ```
+ *
+ * @param ErrorGroup $group [Required] The group which replaces the resource on the server.
+ * @param array $optionalArgs {
+ * Optional.
+ *
+ * @type \Google\GAX\RetrySettings $retrySettings
+ * Retry settings to use for this call. If present, then
+ * $timeoutMillis is ignored.
+ * @type int $timeoutMillis
+ * Timeout to use for this call. Only used if $retrySettings
+ * is not set.
+ * }
+ *
+ * @return \Google\Devtools\Clouderrorreporting\V1beta1\ErrorGroup
+ *
+ * @throws \Google\GAX\ApiException if the remote call fails
+ * @experimental
+ */
+ public function updateGroup($group, $optionalArgs = [])
+ {
+ $request = new UpdateGroupRequest();
+ $request->setGroup($group);
+
+ $mergedSettings = $this->defaultCallSettings['updateGroup']->merge(
+ new CallSettings($optionalArgs)
+ );
+ $callable = ApiCallable::createApiCall(
+ $this->errorGroupServiceStub,
+ 'UpdateGroup',
+ $mergedSettings,
+ $this->descriptors['updateGroup']
+ );
+
+ return $callable(
+ $request,
+ [],
+ ['call_credentials_callback' => $this->createCredentialsCallback()]);
+ }
+
+ /**
+ * Initiates an orderly shutdown in which preexisting calls continue but new
+ * calls are immediately cancelled.
+ *
+ * @experimental
+ */
+ public function close()
+ {
+ $this->errorGroupServiceStub->close();
+ }
+
+ private function createCredentialsCallback()
+ {
+ return $this->grpcCredentialsHelper->createCallCredentialsCallback();
+ }
+}
diff --git a/src/ErrorReporting/V1beta1/Gapic/ErrorStatsServiceGapicClient.php b/src/ErrorReporting/V1beta1/Gapic/ErrorStatsServiceGapicClient.php
new file mode 100644
index 000000000000..40ea53b5eec9
--- /dev/null
+++ b/src/ErrorReporting/V1beta1/Gapic/ErrorStatsServiceGapicClient.php
@@ -0,0 +1,604 @@
+listGroupStats($formattedProjectName, $timeRange);
+ * foreach ($pagedResponse->iterateAllElements() as $element) {
+ * // doSomethingWith($element);
+ * }
+ *
+ * // OR iterate over pages of elements, with the maximum page size set to 5
+ * $pagedResponse = $errorStatsServiceClient->listGroupStats($formattedProjectName, $timeRange, ['pageSize' => 5]);
+ * foreach ($pagedResponse->iteratePages() as $page) {
+ * foreach ($page as $element) {
+ * // doSomethingWith($element);
+ * }
+ * }
+ * } finally {
+ * $errorStatsServiceClient->close();
+ * }
+ * ```
+ *
+ * Many parameters require resource names to be formatted in a particular way. To assist
+ * with these names, this class includes a format method for each type of name, and additionally
+ * a parse method to extract the individual identifiers contained within names that are
+ * returned.
+ *
+ * @experimental
+ */
+class ErrorStatsServiceGapicClient
+{
+ /**
+ * The default address of the service.
+ */
+ const SERVICE_ADDRESS = 'clouderrorreporting.googleapis.com';
+
+ /**
+ * The default port of the service.
+ */
+ const DEFAULT_SERVICE_PORT = 443;
+
+ /**
+ * The default timeout for non-retrying methods.
+ */
+ const DEFAULT_TIMEOUT_MILLIS = 30000;
+
+ /**
+ * The name of the code generator, to be included in the agent header.
+ */
+ const CODEGEN_NAME = 'gapic';
+
+ /**
+ * The code generator version, to be included in the agent header.
+ */
+ const CODEGEN_VERSION = '0.0.5';
+
+ private static $projectNameTemplate;
+
+ protected $grpcCredentialsHelper;
+ protected $errorStatsServiceStub;
+ private $scopes;
+ private $defaultCallSettings;
+ private $descriptors;
+
+ /**
+ * Formats a string containing the fully-qualified path to represent
+ * a project resource.
+ *
+ * @param string $project
+ *
+ * @return string The formatted project resource.
+ * @experimental
+ */
+ public static function formatProjectName($project)
+ {
+ return self::getProjectNameTemplate()->render([
+ 'project' => $project,
+ ]);
+ }
+
+ /**
+ * Parses the project from the given fully-qualified path which
+ * represents a project resource.
+ *
+ * @param string $projectName The fully-qualified project resource.
+ *
+ * @return string The extracted project value.
+ * @experimental
+ */
+ public static function parseProjectFromProjectName($projectName)
+ {
+ return self::getProjectNameTemplate()->match($projectName)['project'];
+ }
+
+ private static function getProjectNameTemplate()
+ {
+ if (self::$projectNameTemplate == null) {
+ self::$projectNameTemplate = new PathTemplate('projects/{project}');
+ }
+
+ return self::$projectNameTemplate;
+ }
+
+ private static function getPageStreamingDescriptors()
+ {
+ $listGroupStatsPageStreamingDescriptor =
+ new PageStreamingDescriptor([
+ 'requestPageTokenGetMethod' => 'getPageToken',
+ 'requestPageTokenSetMethod' => 'setPageToken',
+ 'requestPageSizeGetMethod' => 'getPageSize',
+ 'requestPageSizeSetMethod' => 'setPageSize',
+ 'responsePageTokenGetMethod' => 'getNextPageToken',
+ 'resourcesGetMethod' => 'getErrorGroupStats',
+ ]);
+ $listEventsPageStreamingDescriptor =
+ new PageStreamingDescriptor([
+ 'requestPageTokenGetMethod' => 'getPageToken',
+ 'requestPageTokenSetMethod' => 'setPageToken',
+ 'requestPageSizeGetMethod' => 'getPageSize',
+ 'requestPageSizeSetMethod' => 'setPageSize',
+ 'responsePageTokenGetMethod' => 'getNextPageToken',
+ 'resourcesGetMethod' => 'getErrorEvents',
+ ]);
+
+ $pageStreamingDescriptors = [
+ 'listGroupStats' => $listGroupStatsPageStreamingDescriptor,
+ 'listEvents' => $listEventsPageStreamingDescriptor,
+ ];
+
+ return $pageStreamingDescriptors;
+ }
+
+ private static function getGapicVersion()
+ {
+ if (file_exists(__DIR__.'/../VERSION')) {
+ return trim(file_get_contents(__DIR__.'/../VERSION'));
+ } elseif (class_exists('\Google\Cloud\ServiceBuilder')) {
+ return \Google\Cloud\ServiceBuilder::VERSION;
+ } else {
+ return;
+ }
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param array $options {
+ * Optional. Options for configuring the service API wrapper.
+ *
+ * @type string $serviceAddress The domain name of the API remote host.
+ * Default 'clouderrorreporting.googleapis.com'.
+ * @type mixed $port The port on which to connect to the remote host. Default 443.
+ * @type \Grpc\Channel $channel
+ * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed.
+ * @type \Grpc\ChannelCredentials $sslCreds
+ * A `ChannelCredentials` object for use with an SSL-enabled channel.
+ * Default: a credentials object returned from
+ * \Grpc\ChannelCredentials::createSsl()
+ * NOTE: if the $channel optional argument is specified, then this argument is unused.
+ * @type bool $forceNewChannel
+ * If true, this forces gRPC to create a new channel instead of using a persistent channel.
+ * Defaults to false.
+ * NOTE: if the $channel optional argument is specified, then this option is unused.
+ * @type \Google\Auth\CredentialsLoader $credentialsLoader
+ * A CredentialsLoader object created using the Google\Auth library.
+ * @type array $scopes A string array of scopes to use when acquiring credentials.
+ * Defaults to the scopes for the Stackdriver Error Reporting API.
+ * @type array $retryingOverride
+ * An associative array of string => RetryOptions, where the keys
+ * are method names (e.g. 'createFoo'), that overrides default retrying
+ * settings. A value of null indicates that the method in question should
+ * not retry.
+ * @type int $timeoutMillis The timeout in milliseconds to use for calls
+ * that don't use retries. For calls that use retries,
+ * set the timeout in RetryOptions.
+ * Default: 30000 (30 seconds)
+ * }
+ * @experimental
+ */
+ public function __construct($options = [])
+ {
+ $defaultOptions = [
+ 'serviceAddress' => self::SERVICE_ADDRESS,
+ 'port' => self::DEFAULT_SERVICE_PORT,
+ 'scopes' => [
+ 'https://www.googleapis.com/auth/cloud-platform',
+ ],
+ 'retryingOverride' => null,
+ 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS,
+ 'libName' => null,
+ 'libVersion' => null,
+ ];
+ $options = array_merge($defaultOptions, $options);
+
+ $gapicVersion = $options['libVersion'] ?: self::getGapicVersion();
+
+ $headerDescriptor = new AgentHeaderDescriptor([
+ 'libName' => $options['libName'],
+ 'libVersion' => $options['libVersion'],
+ 'gapicVersion' => $gapicVersion,
+ ]);
+
+ $defaultDescriptors = ['headerDescriptor' => $headerDescriptor];
+ $this->descriptors = [
+ 'listGroupStats' => $defaultDescriptors,
+ 'listEvents' => $defaultDescriptors,
+ 'deleteEvents' => $defaultDescriptors,
+ ];
+ $pageStreamingDescriptors = self::getPageStreamingDescriptors();
+ foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) {
+ $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor;
+ }
+
+ $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/error_stats_service_client_config.json');
+ $clientConfig = json_decode($clientConfigJsonString, true);
+ $this->defaultCallSettings =
+ CallSettings::load(
+ 'google.devtools.clouderrorreporting.v1beta1.ErrorStatsService',
+ $clientConfig,
+ $options['retryingOverride'],
+ GrpcConstants::getStatusCodeNames(),
+ $options['timeoutMillis']
+ );
+
+ $this->scopes = $options['scopes'];
+
+ $createStubOptions = [];
+ if (array_key_exists('sslCreds', $options)) {
+ $createStubOptions['sslCreds'] = $options['sslCreds'];
+ }
+ $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options);
+
+ $createErrorStatsServiceStubFunction = function ($hostname, $opts, $channel) {
+ return new ErrorStatsServiceGrpcClient($hostname, $opts, $channel);
+ };
+ if (array_key_exists('createErrorStatsServiceStubFunction', $options)) {
+ $createErrorStatsServiceStubFunction = $options['createErrorStatsServiceStubFunction'];
+ }
+ $this->errorStatsServiceStub = $this->grpcCredentialsHelper->createStub($createErrorStatsServiceStubFunction);
+ }
+
+ /**
+ * Lists the specified groups.
+ *
+ * Sample code:
+ * ```
+ * try {
+ * $errorStatsServiceClient = new ErrorStatsServiceClient();
+ * $formattedProjectName = ErrorStatsServiceClient::formatProjectName("[PROJECT]");
+ * $timeRange = new QueryTimeRange();
+ * // Iterate through all elements
+ * $pagedResponse = $errorStatsServiceClient->listGroupStats($formattedProjectName, $timeRange);
+ * foreach ($pagedResponse->iterateAllElements() as $element) {
+ * // doSomethingWith($element);
+ * }
+ *
+ * // OR iterate over pages of elements, with the maximum page size set to 5
+ * $pagedResponse = $errorStatsServiceClient->listGroupStats($formattedProjectName, $timeRange, ['pageSize' => 5]);
+ * foreach ($pagedResponse->iteratePages() as $page) {
+ * foreach ($page as $element) {
+ * // doSomethingWith($element);
+ * }
+ * }
+ * } finally {
+ * $errorStatsServiceClient->close();
+ * }
+ * ```
+ *
+ * @param string $projectName [Required] The resource name of the Google Cloud Platform project. Written
+ * as projects/ plus the
+ * Google Cloud
+ * Platform project ID.
+ *
+ * Example: projects/my-project-123.
+ * @param QueryTimeRange $timeRange [Optional] List data for the given time range.
+ * If not set a default time range is used. The field time_range_begin
+ * in the response will specify the beginning of this time range.
+ * Only ErrorGroupStats with a non-zero count in the given time
+ * range are returned, unless the request contains an explicit group_id list.
+ * If a group_id list is given, also ErrorGroupStats with zero
+ * occurrences are returned.
+ * @param array $optionalArgs {
+ * Optional.
+ *
+ * @type string[] $groupId
+ * [Optional] List all ErrorGroupStats with these IDs.
+ * @type ServiceContextFilter $serviceFilter
+ * [Optional] List only ErrorGroupStats which belong to a service
+ * context that matches the filter.
+ * Data for all service contexts is returned if this field is not specified.
+ * @type Duration $timedCountDuration
+ * [Optional] The preferred duration for a single returned `TimedCount`.
+ * If not set, no timed counts are returned.
+ * @type int $alignment
+ * [Optional] The alignment of the timed counts to be returned.
+ * Default is `ALIGNMENT_EQUAL_AT_END`.
+ * For allowed values, use constants defined on {@see \Google\Devtools\Clouderrorreporting\V1beta1\TimedCountAlignment}
+ * @type Timestamp $alignmentTime
+ * [Optional] Time where the timed counts shall be aligned if rounded
+ * alignment is chosen. Default is 00:00 UTC.
+ * @type int $order
+ * [Optional] The sort order in which the results are returned.
+ * Default is `COUNT_DESC`.
+ * For allowed values, use constants defined on {@see \Google\Devtools\Clouderrorreporting\V1beta1\ErrorGroupOrder}
+ * @type int $pageSize
+ * The maximum number of resources contained in the underlying API
+ * response. The API may return fewer values in a page, even if
+ * there are additional values to be retrieved.
+ * @type string $pageToken
+ * A page token is used to specify a page of values to be returned.
+ * If no page token is specified (the default), the first page
+ * of values will be returned. Any page token used here must have
+ * been generated by a previous call to the API.
+ * @type \Google\GAX\RetrySettings $retrySettings
+ * Retry settings to use for this call. If present, then
+ * $timeoutMillis is ignored.
+ * @type int $timeoutMillis
+ * Timeout to use for this call. Only used if $retrySettings
+ * is not set.
+ * }
+ *
+ * @return \Google\GAX\PagedListResponse
+ *
+ * @throws \Google\GAX\ApiException if the remote call fails
+ * @experimental
+ */
+ public function listGroupStats($projectName, $timeRange, $optionalArgs = [])
+ {
+ $request = new ListGroupStatsRequest();
+ $request->setProjectName($projectName);
+ $request->setTimeRange($timeRange);
+ if (isset($optionalArgs['groupId'])) {
+ $request->setGroupId($optionalArgs['groupId']);
+ }
+ if (isset($optionalArgs['serviceFilter'])) {
+ $request->setServiceFilter($optionalArgs['serviceFilter']);
+ }
+ if (isset($optionalArgs['timedCountDuration'])) {
+ $request->setTimedCountDuration($optionalArgs['timedCountDuration']);
+ }
+ if (isset($optionalArgs['alignment'])) {
+ $request->setAlignment($optionalArgs['alignment']);
+ }
+ if (isset($optionalArgs['alignmentTime'])) {
+ $request->setAlignmentTime($optionalArgs['alignmentTime']);
+ }
+ if (isset($optionalArgs['order'])) {
+ $request->setOrder($optionalArgs['order']);
+ }
+ if (isset($optionalArgs['pageSize'])) {
+ $request->setPageSize($optionalArgs['pageSize']);
+ }
+ if (isset($optionalArgs['pageToken'])) {
+ $request->setPageToken($optionalArgs['pageToken']);
+ }
+
+ $mergedSettings = $this->defaultCallSettings['listGroupStats']->merge(
+ new CallSettings($optionalArgs)
+ );
+ $callable = ApiCallable::createApiCall(
+ $this->errorStatsServiceStub,
+ 'ListGroupStats',
+ $mergedSettings,
+ $this->descriptors['listGroupStats']
+ );
+
+ return $callable(
+ $request,
+ [],
+ ['call_credentials_callback' => $this->createCredentialsCallback()]);
+ }
+
+ /**
+ * Lists the specified events.
+ *
+ * Sample code:
+ * ```
+ * try {
+ * $errorStatsServiceClient = new ErrorStatsServiceClient();
+ * $formattedProjectName = ErrorStatsServiceClient::formatProjectName("[PROJECT]");
+ * $groupId = "";
+ * // Iterate through all elements
+ * $pagedResponse = $errorStatsServiceClient->listEvents($formattedProjectName, $groupId);
+ * foreach ($pagedResponse->iterateAllElements() as $element) {
+ * // doSomethingWith($element);
+ * }
+ *
+ * // OR iterate over pages of elements, with the maximum page size set to 5
+ * $pagedResponse = $errorStatsServiceClient->listEvents($formattedProjectName, $groupId, ['pageSize' => 5]);
+ * foreach ($pagedResponse->iteratePages() as $page) {
+ * foreach ($page as $element) {
+ * // doSomethingWith($element);
+ * }
+ * }
+ * } finally {
+ * $errorStatsServiceClient->close();
+ * }
+ * ```
+ *
+ * @param string $projectName [Required] The resource name of the Google Cloud Platform project. Written
+ * as `projects/` plus the
+ * [Google Cloud Platform project
+ * ID](https://support.google.com/cloud/answer/6158840).
+ * Example: `projects/my-project-123`.
+ * @param string $groupId [Required] The group for which events shall be returned.
+ * @param array $optionalArgs {
+ * Optional.
+ *
+ * @type ServiceContextFilter $serviceFilter
+ * [Optional] List only ErrorGroups which belong to a service context that
+ * matches the filter.
+ * Data for all service contexts is returned if this field is not specified.
+ * @type QueryTimeRange $timeRange
+ * [Optional] List only data for the given time range.
+ * If not set a default time range is used. The field time_range_begin
+ * in the response will specify the beginning of this time range.
+ * @type int $pageSize
+ * The maximum number of resources contained in the underlying API
+ * response. The API may return fewer values in a page, even if
+ * there are additional values to be retrieved.
+ * @type string $pageToken
+ * A page token is used to specify a page of values to be returned.
+ * If no page token is specified (the default), the first page
+ * of values will be returned. Any page token used here must have
+ * been generated by a previous call to the API.
+ * @type \Google\GAX\RetrySettings $retrySettings
+ * Retry settings to use for this call. If present, then
+ * $timeoutMillis is ignored.
+ * @type int $timeoutMillis
+ * Timeout to use for this call. Only used if $retrySettings
+ * is not set.
+ * }
+ *
+ * @return \Google\GAX\PagedListResponse
+ *
+ * @throws \Google\GAX\ApiException if the remote call fails
+ * @experimental
+ */
+ public function listEvents($projectName, $groupId, $optionalArgs = [])
+ {
+ $request = new ListEventsRequest();
+ $request->setProjectName($projectName);
+ $request->setGroupId($groupId);
+ if (isset($optionalArgs['serviceFilter'])) {
+ $request->setServiceFilter($optionalArgs['serviceFilter']);
+ }
+ if (isset($optionalArgs['timeRange'])) {
+ $request->setTimeRange($optionalArgs['timeRange']);
+ }
+ if (isset($optionalArgs['pageSize'])) {
+ $request->setPageSize($optionalArgs['pageSize']);
+ }
+ if (isset($optionalArgs['pageToken'])) {
+ $request->setPageToken($optionalArgs['pageToken']);
+ }
+
+ $mergedSettings = $this->defaultCallSettings['listEvents']->merge(
+ new CallSettings($optionalArgs)
+ );
+ $callable = ApiCallable::createApiCall(
+ $this->errorStatsServiceStub,
+ 'ListEvents',
+ $mergedSettings,
+ $this->descriptors['listEvents']
+ );
+
+ return $callable(
+ $request,
+ [],
+ ['call_credentials_callback' => $this->createCredentialsCallback()]);
+ }
+
+ /**
+ * Deletes all error events of a given project.
+ *
+ * Sample code:
+ * ```
+ * try {
+ * $errorStatsServiceClient = new ErrorStatsServiceClient();
+ * $formattedProjectName = ErrorStatsServiceClient::formatProjectName("[PROJECT]");
+ * $response = $errorStatsServiceClient->deleteEvents($formattedProjectName);
+ * } finally {
+ * $errorStatsServiceClient->close();
+ * }
+ * ```
+ *
+ * @param string $projectName [Required] The resource name of the Google Cloud Platform project. Written
+ * as `projects/` plus the
+ * [Google Cloud Platform project
+ * ID](https://support.google.com/cloud/answer/6158840).
+ * Example: `projects/my-project-123`.
+ * @param array $optionalArgs {
+ * Optional.
+ *
+ * @type \Google\GAX\RetrySettings $retrySettings
+ * Retry settings to use for this call. If present, then
+ * $timeoutMillis is ignored.
+ * @type int $timeoutMillis
+ * Timeout to use for this call. Only used if $retrySettings
+ * is not set.
+ * }
+ *
+ * @return \Google\Devtools\Clouderrorreporting\V1beta1\DeleteEventsResponse
+ *
+ * @throws \Google\GAX\ApiException if the remote call fails
+ * @experimental
+ */
+ public function deleteEvents($projectName, $optionalArgs = [])
+ {
+ $request = new DeleteEventsRequest();
+ $request->setProjectName($projectName);
+
+ $mergedSettings = $this->defaultCallSettings['deleteEvents']->merge(
+ new CallSettings($optionalArgs)
+ );
+ $callable = ApiCallable::createApiCall(
+ $this->errorStatsServiceStub,
+ 'DeleteEvents',
+ $mergedSettings,
+ $this->descriptors['deleteEvents']
+ );
+
+ return $callable(
+ $request,
+ [],
+ ['call_credentials_callback' => $this->createCredentialsCallback()]);
+ }
+
+ /**
+ * Initiates an orderly shutdown in which preexisting calls continue but new
+ * calls are immediately cancelled.
+ *
+ * @experimental
+ */
+ public function close()
+ {
+ $this->errorStatsServiceStub->close();
+ }
+
+ private function createCredentialsCallback()
+ {
+ return $this->grpcCredentialsHelper->createCallCredentialsCallback();
+ }
+}
diff --git a/src/ErrorReporting/V1beta1/Gapic/ReportErrorsServiceGapicClient.php b/src/ErrorReporting/V1beta1/Gapic/ReportErrorsServiceGapicClient.php
new file mode 100644
index 000000000000..6872418f026b
--- /dev/null
+++ b/src/ErrorReporting/V1beta1/Gapic/ReportErrorsServiceGapicClient.php
@@ -0,0 +1,328 @@
+reportErrorEvent($formattedProjectName, $event);
+ * } finally {
+ * $reportErrorsServiceClient->close();
+ * }
+ * ```
+ *
+ * Many parameters require resource names to be formatted in a particular way. To assist
+ * with these names, this class includes a format method for each type of name, and additionally
+ * a parse method to extract the individual identifiers contained within names that are
+ * returned.
+ *
+ * @experimental
+ */
+class ReportErrorsServiceGapicClient
+{
+ /**
+ * The default address of the service.
+ */
+ const SERVICE_ADDRESS = 'clouderrorreporting.googleapis.com';
+
+ /**
+ * The default port of the service.
+ */
+ const DEFAULT_SERVICE_PORT = 443;
+
+ /**
+ * The default timeout for non-retrying methods.
+ */
+ const DEFAULT_TIMEOUT_MILLIS = 30000;
+
+ /**
+ * The name of the code generator, to be included in the agent header.
+ */
+ const CODEGEN_NAME = 'gapic';
+
+ /**
+ * The code generator version, to be included in the agent header.
+ */
+ const CODEGEN_VERSION = '0.0.5';
+
+ private static $projectNameTemplate;
+
+ protected $grpcCredentialsHelper;
+ protected $reportErrorsServiceStub;
+ private $scopes;
+ private $defaultCallSettings;
+ private $descriptors;
+
+ /**
+ * Formats a string containing the fully-qualified path to represent
+ * a project resource.
+ *
+ * @param string $project
+ *
+ * @return string The formatted project resource.
+ * @experimental
+ */
+ public static function formatProjectName($project)
+ {
+ return self::getProjectNameTemplate()->render([
+ 'project' => $project,
+ ]);
+ }
+
+ /**
+ * Parses the project from the given fully-qualified path which
+ * represents a project resource.
+ *
+ * @param string $projectName The fully-qualified project resource.
+ *
+ * @return string The extracted project value.
+ * @experimental
+ */
+ public static function parseProjectFromProjectName($projectName)
+ {
+ return self::getProjectNameTemplate()->match($projectName)['project'];
+ }
+
+ private static function getProjectNameTemplate()
+ {
+ if (self::$projectNameTemplate == null) {
+ self::$projectNameTemplate = new PathTemplate('projects/{project}');
+ }
+
+ return self::$projectNameTemplate;
+ }
+
+ private static function getGapicVersion()
+ {
+ if (file_exists(__DIR__.'/../VERSION')) {
+ return trim(file_get_contents(__DIR__.'/../VERSION'));
+ } elseif (class_exists('\Google\Cloud\ServiceBuilder')) {
+ return \Google\Cloud\ServiceBuilder::VERSION;
+ } else {
+ return;
+ }
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param array $options {
+ * Optional. Options for configuring the service API wrapper.
+ *
+ * @type string $serviceAddress The domain name of the API remote host.
+ * Default 'clouderrorreporting.googleapis.com'.
+ * @type mixed $port The port on which to connect to the remote host. Default 443.
+ * @type \Grpc\Channel $channel
+ * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed.
+ * @type \Grpc\ChannelCredentials $sslCreds
+ * A `ChannelCredentials` object for use with an SSL-enabled channel.
+ * Default: a credentials object returned from
+ * \Grpc\ChannelCredentials::createSsl()
+ * NOTE: if the $channel optional argument is specified, then this argument is unused.
+ * @type bool $forceNewChannel
+ * If true, this forces gRPC to create a new channel instead of using a persistent channel.
+ * Defaults to false.
+ * NOTE: if the $channel optional argument is specified, then this option is unused.
+ * @type \Google\Auth\CredentialsLoader $credentialsLoader
+ * A CredentialsLoader object created using the Google\Auth library.
+ * @type array $scopes A string array of scopes to use when acquiring credentials.
+ * Defaults to the scopes for the Stackdriver Error Reporting API.
+ * @type array $retryingOverride
+ * An associative array of string => RetryOptions, where the keys
+ * are method names (e.g. 'createFoo'), that overrides default retrying
+ * settings. A value of null indicates that the method in question should
+ * not retry.
+ * @type int $timeoutMillis The timeout in milliseconds to use for calls
+ * that don't use retries. For calls that use retries,
+ * set the timeout in RetryOptions.
+ * Default: 30000 (30 seconds)
+ * }
+ * @experimental
+ */
+ public function __construct($options = [])
+ {
+ $defaultOptions = [
+ 'serviceAddress' => self::SERVICE_ADDRESS,
+ 'port' => self::DEFAULT_SERVICE_PORT,
+ 'scopes' => [
+ 'https://www.googleapis.com/auth/cloud-platform',
+ ],
+ 'retryingOverride' => null,
+ 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS,
+ 'libName' => null,
+ 'libVersion' => null,
+ ];
+ $options = array_merge($defaultOptions, $options);
+
+ $gapicVersion = $options['libVersion'] ?: self::getGapicVersion();
+
+ $headerDescriptor = new AgentHeaderDescriptor([
+ 'libName' => $options['libName'],
+ 'libVersion' => $options['libVersion'],
+ 'gapicVersion' => $gapicVersion,
+ ]);
+
+ $defaultDescriptors = ['headerDescriptor' => $headerDescriptor];
+ $this->descriptors = [
+ 'reportErrorEvent' => $defaultDescriptors,
+ ];
+
+ $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/report_errors_service_client_config.json');
+ $clientConfig = json_decode($clientConfigJsonString, true);
+ $this->defaultCallSettings =
+ CallSettings::load(
+ 'google.devtools.clouderrorreporting.v1beta1.ReportErrorsService',
+ $clientConfig,
+ $options['retryingOverride'],
+ GrpcConstants::getStatusCodeNames(),
+ $options['timeoutMillis']
+ );
+
+ $this->scopes = $options['scopes'];
+
+ $createStubOptions = [];
+ if (array_key_exists('sslCreds', $options)) {
+ $createStubOptions['sslCreds'] = $options['sslCreds'];
+ }
+ $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options);
+
+ $createReportErrorsServiceStubFunction = function ($hostname, $opts, $channel) {
+ return new ReportErrorsServiceGrpcClient($hostname, $opts, $channel);
+ };
+ if (array_key_exists('createReportErrorsServiceStubFunction', $options)) {
+ $createReportErrorsServiceStubFunction = $options['createReportErrorsServiceStubFunction'];
+ }
+ $this->reportErrorsServiceStub = $this->grpcCredentialsHelper->createStub($createReportErrorsServiceStubFunction);
+ }
+
+ /**
+ * Report an individual error event.
+ *
+ * This endpoint accepts either an OAuth token,
+ * or an
+ * API key
+ * for authentication. To use an API key, append it to the URL as the value of
+ * a `key` parameter. For example:
+ * POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456+ * + * Sample code: + * ``` + * try { + * $reportErrorsServiceClient = new ReportErrorsServiceClient(); + * $formattedProjectName = ReportErrorsServiceClient::formatProjectName("[PROJECT]"); + * $event = new ReportedErrorEvent(); + * $response = $reportErrorsServiceClient->reportErrorEvent($formattedProjectName, $event); + * } finally { + * $reportErrorsServiceClient->close(); + * } + * ``` + * + * @param string $projectName [Required] The resource name of the Google Cloud Platform project. Written + * as `projects/` plus the + * [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840). + * Example: `projects/my-project-123`. + * @param ReportedErrorEvent $event [Required] The error event to be reported. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Devtools\Clouderrorreporting\V1beta1\ReportErrorEventResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function reportErrorEvent($projectName, $event, $optionalArgs = []) + { + $request = new ReportErrorEventRequest(); + $request->setProjectName($projectName); + $request->setEvent($event); + + $mergedSettings = $this->defaultCallSettings['reportErrorEvent']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->reportErrorsServiceStub, + 'ReportErrorEvent', + $mergedSettings, + $this->descriptors['reportErrorEvent'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->reportErrorsServiceStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/ErrorReporting/V1beta1/ReportErrorsServiceClient.php b/src/ErrorReporting/V1beta1/ReportErrorsServiceClient.php index 9ab54bf3ee77..7a9a2439525c 100644 --- a/src/ErrorReporting/V1beta1/ReportErrorsServiceClient.php +++ b/src/ErrorReporting/V1beta1/ReportErrorsServiceClient.php @@ -30,300 +30,12 @@ namespace Google\Cloud\ErrorReporting\V1beta1; -use Google\Devtools\Clouderrorreporting\V1beta1\ReportErrorEventRequest; -use Google\Devtools\Clouderrorreporting\V1beta1\ReportErrorsServiceGrpcClient; -use Google\Devtools\Clouderrorreporting\V1beta1\ReportedErrorEvent; -use Google\GAX\AgentHeaderDescriptor; -use Google\GAX\ApiCallable; -use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; -use Google\GAX\GrpcCredentialsHelper; -use Google\GAX\PathTemplate; +use Google\Cloud\ErrorReporting\V1beta1\Gapic\ReportErrorsServiceGapicClient; /** - * Service Description: An API for reporting error events. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $reportErrorsServiceClient = new ReportErrorsServiceClient(); - * $formattedProjectName = ReportErrorsServiceClient::formatProjectName("[PROJECT]"); - * $event = new ReportedErrorEvent(); - * $response = $reportErrorsServiceClient->reportErrorEvent($formattedProjectName, $event); - * } finally { - * $reportErrorsServiceClient->close(); - * } - * ``` - * - * Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. - * - * @experimental + * {@inheritdoc} */ -class ReportErrorsServiceClient +class ReportErrorsServiceClient extends ReportErrorsServiceGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'clouderrorreporting.googleapis.com'; - - /** - * The default port of the service. - */ - const DEFAULT_SERVICE_PORT = 443; - - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - - /** - * The name of the code generator, to be included in the agent header. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $projectNameTemplate; - - private $grpcCredentialsHelper; - private $reportErrorsServiceStub; - private $scopes; - private $defaultCallSettings; - private $descriptors; - - /** - * Formats a string containing the fully-qualified path to represent - * a project resource. - * - * @param string $project - * - * @return string The formatted project resource. - * @experimental - */ - public static function formatProjectName($project) - { - return self::getProjectNameTemplate()->render([ - 'project' => $project, - ]); - } - - /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - * - * @param string $projectName The fully-qualified project resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromProjectName($projectName) - { - return self::getProjectNameTemplate()->match($projectName)['project']; - } - - private static function getProjectNameTemplate() - { - if (self::$projectNameTemplate == null) { - self::$projectNameTemplate = new PathTemplate('projects/{project}'); - } - - return self::$projectNameTemplate; - } - - private static function getGapicVersion() - { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'clouderrorreporting.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Stackdriver Error Reporting API. - * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'reportErrorEvent' => $defaultDescriptors, - ]; - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/report_errors_service_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.devtools.clouderrorreporting.v1beta1.ReportErrorsService', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createReportErrorsServiceStubFunction = function ($hostname, $opts) { - return new ReportErrorsServiceGrpcClient($hostname, $opts); - }; - if (array_key_exists('createReportErrorsServiceStubFunction', $options)) { - $createReportErrorsServiceStubFunction = $options['createReportErrorsServiceStubFunction']; - } - $this->reportErrorsServiceStub = $this->grpcCredentialsHelper->createStub( - $createReportErrorsServiceStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Report an individual error event. - * - * This endpoint accepts either an OAuth token, - * or an - * API key - * for authentication. To use an API key, append it to the URL as the value of - * a `key` parameter. For example: - *
POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456- * - * Sample code: - * ``` - * try { - * $reportErrorsServiceClient = new ReportErrorsServiceClient(); - * $formattedProjectName = ReportErrorsServiceClient::formatProjectName("[PROJECT]"); - * $event = new ReportedErrorEvent(); - * $response = $reportErrorsServiceClient->reportErrorEvent($formattedProjectName, $event); - * } finally { - * $reportErrorsServiceClient->close(); - * } - * ``` - * - * @param string $projectName [Required] The resource name of the Google Cloud Platform project. Written - * as `projects/` plus the - * [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840). - * Example: `projects/my-project-123`. - * @param ReportedErrorEvent $event [Required] The error event to be reported. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Devtools\Clouderrorreporting\V1beta1\ReportErrorEventResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function reportErrorEvent($projectName, $event, $optionalArgs = []) - { - $request = new ReportErrorEventRequest(); - $request->setProjectName($projectName); - $request->setEvent($event); - - $mergedSettings = $this->defaultCallSettings['reportErrorEvent']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->reportErrorsServiceStub, - 'ReportErrorEvent', - $mergedSettings, - $this->descriptors['reportErrorEvent'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->reportErrorsServiceStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see ReportErrorsServiceClientImpl} class. } diff --git a/src/ErrorReporting/composer.json b/src/ErrorReporting/composer.json index b17c545a3af1..42f5bfbbfd64 100644 --- a/src/ErrorReporting/composer.json +++ b/src/ErrorReporting/composer.json @@ -5,8 +5,8 @@ "minimum-stability": "stable", "require": { "ext-grpc": "*", - "google/proto-client": "^0.21.0", - "google/gax": "^0.21.0" + "google/proto-client": "^0.22.0", + "google/gax": "^0.22.1" }, "extra": { "component": { diff --git a/src/Language/V1beta2/Gapic/LanguageServiceGapicClient.php b/src/Language/V1beta2/Gapic/LanguageServiceGapicClient.php new file mode 100644 index 000000000000..23f7a374567a --- /dev/null +++ b/src/Language/V1beta2/Gapic/LanguageServiceGapicClient.php @@ -0,0 +1,526 @@ +analyzeSentiment($document); + * } finally { + * $languageServiceClient->close(); + * } + * ``` + * + * @experimental + */ +class LanguageServiceGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'language.googleapis.com'; + + /** + * The default port of the service. + */ + const DEFAULT_SERVICE_PORT = 443; + + /** + * The default timeout for non-retrying methods. + */ + const DEFAULT_TIMEOUT_MILLIS = 30000; + + /** + * The name of the code generator, to be included in the agent header. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + protected $grpcCredentialsHelper; + protected $languageServiceStub; + private $scopes; + private $defaultCallSettings; + private $descriptors; + + private static function getGapicVersion() + { + if (file_exists(__DIR__.'/../VERSION')) { + return trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { + return \Google\Cloud\ServiceBuilder::VERSION; + } else { + return; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'language.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * A CredentialsLoader object created using the Google\Auth library. + * @type array $scopes A string array of scopes to use when acquiring credentials. + * Defaults to the scopes for the Google Cloud Natural Language API. + * @type array $retryingOverride + * An associative array of string => RetryOptions, where the keys + * are method names (e.g. 'createFoo'), that overrides default retrying + * settings. A value of null indicates that the method in question should + * not retry. + * @type int $timeoutMillis The timeout in milliseconds to use for calls + * that don't use retries. For calls that use retries, + * set the timeout in RetryOptions. + * Default: 30000 (30 seconds) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'analyzeSentiment' => $defaultDescriptors, + 'analyzeEntities' => $defaultDescriptors, + 'analyzeEntitySentiment' => $defaultDescriptors, + 'analyzeSyntax' => $defaultDescriptors, + 'annotateText' => $defaultDescriptors, + ]; + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/language_service_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.cloud.language.v1beta2.LanguageService', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createLanguageServiceStubFunction = function ($hostname, $opts, $channel) { + return new LanguageServiceGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createLanguageServiceStubFunction', $options)) { + $createLanguageServiceStubFunction = $options['createLanguageServiceStubFunction']; + } + $this->languageServiceStub = $this->grpcCredentialsHelper->createStub($createLanguageServiceStubFunction); + } + + /** + * Analyzes the sentiment of the provided text. + * + * Sample code: + * ``` + * try { + * $languageServiceClient = new LanguageServiceClient(); + * $document = new Document(); + * $response = $languageServiceClient->analyzeSentiment($document); + * } finally { + * $languageServiceClient->close(); + * } + * ``` + * + * @param Document $document Input document. + * @param array $optionalArgs { + * Optional. + * + * @type int $encodingType + * The encoding type used by the API to calculate sentence offsets for the + * sentence sentiment. + * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1beta2\EncodingType} + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Cloud\Language\V1beta2\AnalyzeSentimentResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function analyzeSentiment($document, $optionalArgs = []) + { + $request = new AnalyzeSentimentRequest(); + $request->setDocument($document); + if (isset($optionalArgs['encodingType'])) { + $request->setEncodingType($optionalArgs['encodingType']); + } + + $mergedSettings = $this->defaultCallSettings['analyzeSentiment']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->languageServiceStub, + 'AnalyzeSentiment', + $mergedSettings, + $this->descriptors['analyzeSentiment'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Finds named entities (currently proper names and common nouns) in the text + * along with entity types, salience, mentions for each entity, and + * other properties. + * + * Sample code: + * ``` + * try { + * $languageServiceClient = new LanguageServiceClient(); + * $document = new Document(); + * $response = $languageServiceClient->analyzeEntities($document); + * } finally { + * $languageServiceClient->close(); + * } + * ``` + * + * @param Document $document Input document. + * @param array $optionalArgs { + * Optional. + * + * @type int $encodingType + * The encoding type used by the API to calculate offsets. + * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1beta2\EncodingType} + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Cloud\Language\V1beta2\AnalyzeEntitiesResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function analyzeEntities($document, $optionalArgs = []) + { + $request = new AnalyzeEntitiesRequest(); + $request->setDocument($document); + if (isset($optionalArgs['encodingType'])) { + $request->setEncodingType($optionalArgs['encodingType']); + } + + $mergedSettings = $this->defaultCallSettings['analyzeEntities']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->languageServiceStub, + 'AnalyzeEntities', + $mergedSettings, + $this->descriptors['analyzeEntities'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text and analyzes + * sentiment associated with each entity and its mentions. + * + * Sample code: + * ``` + * try { + * $languageServiceClient = new LanguageServiceClient(); + * $document = new Document(); + * $response = $languageServiceClient->analyzeEntitySentiment($document); + * } finally { + * $languageServiceClient->close(); + * } + * ``` + * + * @param Document $document Input document. + * @param array $optionalArgs { + * Optional. + * + * @type int $encodingType + * The encoding type used by the API to calculate offsets. + * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1beta2\EncodingType} + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Cloud\Language\V1beta2\AnalyzeEntitySentimentResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function analyzeEntitySentiment($document, $optionalArgs = []) + { + $request = new AnalyzeEntitySentimentRequest(); + $request->setDocument($document); + if (isset($optionalArgs['encodingType'])) { + $request->setEncodingType($optionalArgs['encodingType']); + } + + $mergedSettings = $this->defaultCallSettings['analyzeEntitySentiment']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->languageServiceStub, + 'AnalyzeEntitySentiment', + $mergedSettings, + $this->descriptors['analyzeEntitySentiment'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Analyzes the syntax of the text and provides sentence boundaries and + * tokenization along with part of speech tags, dependency trees, and other + * properties. + * + * Sample code: + * ``` + * try { + * $languageServiceClient = new LanguageServiceClient(); + * $document = new Document(); + * $response = $languageServiceClient->analyzeSyntax($document); + * } finally { + * $languageServiceClient->close(); + * } + * ``` + * + * @param Document $document Input document. + * @param array $optionalArgs { + * Optional. + * + * @type int $encodingType + * The encoding type used by the API to calculate offsets. + * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1beta2\EncodingType} + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Cloud\Language\V1beta2\AnalyzeSyntaxResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function analyzeSyntax($document, $optionalArgs = []) + { + $request = new AnalyzeSyntaxRequest(); + $request->setDocument($document); + if (isset($optionalArgs['encodingType'])) { + $request->setEncodingType($optionalArgs['encodingType']); + } + + $mergedSettings = $this->defaultCallSettings['analyzeSyntax']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->languageServiceStub, + 'AnalyzeSyntax', + $mergedSettings, + $this->descriptors['analyzeSyntax'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * A convenience method that provides all syntax, sentiment, and entity + * features in one call. + * + * Sample code: + * ``` + * try { + * $languageServiceClient = new LanguageServiceClient(); + * $document = new Document(); + * $features = new Features(); + * $response = $languageServiceClient->annotateText($document, $features); + * } finally { + * $languageServiceClient->close(); + * } + * ``` + * + * @param Document $document Input document. + * @param Features $features The enabled features. + * @param array $optionalArgs { + * Optional. + * + * @type int $encodingType + * The encoding type used by the API to calculate offsets. + * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1beta2\EncodingType} + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Cloud\Language\V1beta2\AnnotateTextResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function annotateText($document, $features, $optionalArgs = []) + { + $request = new AnnotateTextRequest(); + $request->setDocument($document); + $request->setFeatures($features); + if (isset($optionalArgs['encodingType'])) { + $request->setEncodingType($optionalArgs['encodingType']); + } + + $mergedSettings = $this->defaultCallSettings['annotateText']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->languageServiceStub, + 'AnnotateText', + $mergedSettings, + $this->descriptors['annotateText'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->languageServiceStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/Language/V1beta2/LanguageServiceClient.php b/src/Language/V1beta2/LanguageServiceClient.php index 6a3d98151102..b8a7739d598b 100644 --- a/src/Language/V1beta2/LanguageServiceClient.php +++ b/src/Language/V1beta2/LanguageServiceClient.php @@ -30,482 +30,12 @@ namespace Google\Cloud\Language\V1beta2; -use Google\Cloud\Language\V1beta2\AnnotateTextRequest_Features as Features; -use Google\GAX\AgentHeaderDescriptor; -use Google\GAX\ApiCallable; -use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; -use Google\GAX\GrpcCredentialsHelper; +use Google\Cloud\Language\V1beta2\Gapic\LanguageServiceGapicClient; /** - * Service Description: Provides text analysis operations such as sentiment analysis and entity - * recognition. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $languageServiceClient = new LanguageServiceClient(); - * $document = new Document(); - * $response = $languageServiceClient->analyzeSentiment($document); - * } finally { - * $languageServiceClient->close(); - * } - * ``` - * - * @experimental + * {@inheritdoc} */ -class LanguageServiceClient +class LanguageServiceClient extends LanguageServiceGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'language.googleapis.com'; - - /** - * The default port of the service. - */ - const DEFAULT_SERVICE_PORT = 443; - - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - - /** - * The name of the code generator, to be included in the agent header. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private $grpcCredentialsHelper; - private $languageServiceStub; - private $scopes; - private $defaultCallSettings; - private $descriptors; - - private static function getGapicVersion() - { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'language.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Google Cloud Natural Language API. - * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'analyzeSentiment' => $defaultDescriptors, - 'analyzeEntities' => $defaultDescriptors, - 'analyzeEntitySentiment' => $defaultDescriptors, - 'analyzeSyntax' => $defaultDescriptors, - 'annotateText' => $defaultDescriptors, - ]; - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/language_service_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.cloud.language.v1beta2.LanguageService', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createLanguageServiceStubFunction = function ($hostname, $opts) { - return new LanguageServiceGrpcClient($hostname, $opts); - }; - if (array_key_exists('createLanguageServiceStubFunction', $options)) { - $createLanguageServiceStubFunction = $options['createLanguageServiceStubFunction']; - } - $this->languageServiceStub = $this->grpcCredentialsHelper->createStub( - $createLanguageServiceStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Analyzes the sentiment of the provided text. - * - * Sample code: - * ``` - * try { - * $languageServiceClient = new LanguageServiceClient(); - * $document = new Document(); - * $response = $languageServiceClient->analyzeSentiment($document); - * } finally { - * $languageServiceClient->close(); - * } - * ``` - * - * @param Document $document Input document. - * @param array $optionalArgs { - * Optional. - * - * @type int $encodingType - * The encoding type used by the API to calculate sentence offsets for the - * sentence sentiment. - * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1beta2\EncodingType} - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Cloud\Language\V1beta2\AnalyzeSentimentResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function analyzeSentiment($document, $optionalArgs = []) - { - $request = new AnalyzeSentimentRequest(); - $request->setDocument($document); - if (isset($optionalArgs['encodingType'])) { - $request->setEncodingType($optionalArgs['encodingType']); - } - - $mergedSettings = $this->defaultCallSettings['analyzeSentiment']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->languageServiceStub, - 'AnalyzeSentiment', - $mergedSettings, - $this->descriptors['analyzeSentiment'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Finds named entities (currently proper names and common nouns) in the text - * along with entity types, salience, mentions for each entity, and - * other properties. - * - * Sample code: - * ``` - * try { - * $languageServiceClient = new LanguageServiceClient(); - * $document = new Document(); - * $encodingType = EncodingType::NONE; - * $response = $languageServiceClient->analyzeEntities($document, $encodingType); - * } finally { - * $languageServiceClient->close(); - * } - * ``` - * - * @param Document $document Input document. - * @param int $encodingType The encoding type used by the API to calculate offsets. - * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1beta2\EncodingType} - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Cloud\Language\V1beta2\AnalyzeEntitiesResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function analyzeEntities($document, $encodingType, $optionalArgs = []) - { - $request = new AnalyzeEntitiesRequest(); - $request->setDocument($document); - $request->setEncodingType($encodingType); - - $mergedSettings = $this->defaultCallSettings['analyzeEntities']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->languageServiceStub, - 'AnalyzeEntities', - $mergedSettings, - $this->descriptors['analyzeEntities'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text and analyzes - * sentiment associated with each entity and its mentions. - * - * Sample code: - * ``` - * try { - * $languageServiceClient = new LanguageServiceClient(); - * $document = new Document(); - * $encodingType = EncodingType::NONE; - * $response = $languageServiceClient->analyzeEntitySentiment($document, $encodingType); - * } finally { - * $languageServiceClient->close(); - * } - * ``` - * - * @param Document $document Input document. - * @param int $encodingType The encoding type used by the API to calculate offsets. - * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1beta2\EncodingType} - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Cloud\Language\V1beta2\AnalyzeEntitySentimentResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function analyzeEntitySentiment($document, $encodingType, $optionalArgs = []) - { - $request = new AnalyzeEntitySentimentRequest(); - $request->setDocument($document); - $request->setEncodingType($encodingType); - - $mergedSettings = $this->defaultCallSettings['analyzeEntitySentiment']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->languageServiceStub, - 'AnalyzeEntitySentiment', - $mergedSettings, - $this->descriptors['analyzeEntitySentiment'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Analyzes the syntax of the text and provides sentence boundaries and - * tokenization along with part of speech tags, dependency trees, and other - * properties. - * - * Sample code: - * ``` - * try { - * $languageServiceClient = new LanguageServiceClient(); - * $document = new Document(); - * $encodingType = EncodingType::NONE; - * $response = $languageServiceClient->analyzeSyntax($document, $encodingType); - * } finally { - * $languageServiceClient->close(); - * } - * ``` - * - * @param Document $document Input document. - * @param int $encodingType The encoding type used by the API to calculate offsets. - * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1beta2\EncodingType} - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Cloud\Language\V1beta2\AnalyzeSyntaxResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function analyzeSyntax($document, $encodingType, $optionalArgs = []) - { - $request = new AnalyzeSyntaxRequest(); - $request->setDocument($document); - $request->setEncodingType($encodingType); - - $mergedSettings = $this->defaultCallSettings['analyzeSyntax']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->languageServiceStub, - 'AnalyzeSyntax', - $mergedSettings, - $this->descriptors['analyzeSyntax'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * A convenience method that provides all syntax, sentiment, and entity - * features in one call. - * - * Sample code: - * ``` - * try { - * $languageServiceClient = new LanguageServiceClient(); - * $document = new Document(); - * $features = new Features(); - * $encodingType = EncodingType::NONE; - * $response = $languageServiceClient->annotateText($document, $features, $encodingType); - * } finally { - * $languageServiceClient->close(); - * } - * ``` - * - * @param Document $document Input document. - * @param Features $features The enabled features. - * @param int $encodingType The encoding type used by the API to calculate offsets. - * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1beta2\EncodingType} - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Cloud\Language\V1beta2\AnnotateTextResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function annotateText($document, $features, $encodingType, $optionalArgs = []) - { - $request = new AnnotateTextRequest(); - $request->setDocument($document); - $request->setFeatures($features); - $request->setEncodingType($encodingType); - - $mergedSettings = $this->defaultCallSettings['annotateText']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->languageServiceStub, - 'AnnotateText', - $mergedSettings, - $this->descriptors['annotateText'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->languageServiceStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see LanguageServiceClientImpl} class. } diff --git a/src/Logging/V2/ConfigServiceV2Client.php b/src/Logging/V2/ConfigServiceV2Client.php index 57de6e1621d6..f3d39c9f70aa 100644 --- a/src/Logging/V2/ConfigServiceV2Client.php +++ b/src/Logging/V2/ConfigServiceV2Client.php @@ -30,710 +30,12 @@ namespace Google\Cloud\Logging\V2; -use Google\GAX\AgentHeaderDescriptor; -use Google\GAX\ApiCallable; -use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; -use Google\GAX\GrpcCredentialsHelper; -use Google\GAX\PageStreamingDescriptor; -use Google\GAX\PathTemplate; -use Google\Logging\V2\ConfigServiceV2GrpcClient; -use Google\Logging\V2\CreateSinkRequest; -use Google\Logging\V2\DeleteSinkRequest; -use Google\Logging\V2\GetSinkRequest; -use Google\Logging\V2\ListSinksRequest; -use Google\Logging\V2\LogSink; -use Google\Logging\V2\UpdateSinkRequest; +use Google\Cloud\Logging\V2\Gapic\ConfigServiceV2GapicClient; /** - * Service Description: Service for configuring sinks used to export log entries outside of - * Stackdriver Logging. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $configServiceV2Client = new ConfigServiceV2Client(); - * $formattedParent = ConfigServiceV2Client::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $configServiceV2Client->listSinks($formattedParent); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $configServiceV2Client->listSinks($formattedParent, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $configServiceV2Client->close(); - * } - * ``` - * - * Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. - * - * @experimental + * {@inheritdoc} */ -class ConfigServiceV2Client +class ConfigServiceV2Client extends ConfigServiceV2GapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'logging.googleapis.com'; - - /** - * The default port of the service. - */ - const DEFAULT_SERVICE_PORT = 443; - - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - - /** - * The name of the code generator, to be included in the agent header. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $projectNameTemplate; - private static $sinkNameTemplate; - - private $grpcCredentialsHelper; - private $configServiceV2Stub; - private $scopes; - private $defaultCallSettings; - private $descriptors; - - /** - * Formats a string containing the fully-qualified path to represent - * a project resource. - * - * @param string $project - * - * @return string The formatted project resource. - * @experimental - */ - public static function formatProjectName($project) - { - return self::getProjectNameTemplate()->render([ - 'project' => $project, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a sink resource. - * - * @param string $project - * @param string $sink - * - * @return string The formatted sink resource. - * @experimental - */ - public static function formatSinkName($project, $sink) - { - return self::getSinkNameTemplate()->render([ - 'project' => $project, - 'sink' => $sink, - ]); - } - - /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - * - * @param string $projectName The fully-qualified project resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromProjectName($projectName) - { - return self::getProjectNameTemplate()->match($projectName)['project']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a sink resource. - * - * @param string $sinkName The fully-qualified sink resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromSinkName($sinkName) - { - return self::getSinkNameTemplate()->match($sinkName)['project']; - } - - /** - * Parses the sink from the given fully-qualified path which - * represents a sink resource. - * - * @param string $sinkName The fully-qualified sink resource. - * - * @return string The extracted sink value. - * @experimental - */ - public static function parseSinkFromSinkName($sinkName) - { - return self::getSinkNameTemplate()->match($sinkName)['sink']; - } - - private static function getProjectNameTemplate() - { - if (self::$projectNameTemplate == null) { - self::$projectNameTemplate = new PathTemplate('projects/{project}'); - } - - return self::$projectNameTemplate; - } - - private static function getSinkNameTemplate() - { - if (self::$sinkNameTemplate == null) { - self::$sinkNameTemplate = new PathTemplate('projects/{project}/sinks/{sink}'); - } - - return self::$sinkNameTemplate; - } - - private static function getPageStreamingDescriptors() - { - $listSinksPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getSinks', - ]); - - $pageStreamingDescriptors = [ - 'listSinks' => $listSinksPageStreamingDescriptor, - ]; - - return $pageStreamingDescriptors; - } - - private static function getGapicVersion() - { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'logging.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Stackdriver Logging API. - * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'listSinks' => $defaultDescriptors, - 'getSink' => $defaultDescriptors, - 'createSink' => $defaultDescriptors, - 'updateSink' => $defaultDescriptors, - 'deleteSink' => $defaultDescriptors, - ]; - $pageStreamingDescriptors = self::getPageStreamingDescriptors(); - foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { - $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/config_service_v2_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.logging.v2.ConfigServiceV2', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createConfigServiceV2StubFunction = function ($hostname, $opts) { - return new ConfigServiceV2GrpcClient($hostname, $opts); - }; - if (array_key_exists('createConfigServiceV2StubFunction', $options)) { - $createConfigServiceV2StubFunction = $options['createConfigServiceV2StubFunction']; - } - $this->configServiceV2Stub = $this->grpcCredentialsHelper->createStub( - $createConfigServiceV2StubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Lists sinks. - * - * Sample code: - * ``` - * try { - * $configServiceV2Client = new ConfigServiceV2Client(); - * $formattedParent = ConfigServiceV2Client::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $configServiceV2Client->listSinks($formattedParent); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $configServiceV2Client->listSinks($formattedParent, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $configServiceV2Client->close(); - * } - * ``` - * - * @param string $parent Required. The parent resource whose sinks are to be listed: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * @param array $optionalArgs { - * Optional. - * - * @type string $pageToken - * A page token is used to specify a page of values to be returned. - * If no page token is specified (the default), the first page - * of values will be returned. Any page token used here must have - * been generated by a previous call to the API. - * @type int $pageSize - * The maximum number of resources contained in the underlying API - * response. The API may return fewer values in a page, even if - * there are additional values to be retrieved. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listSinks($parent, $optionalArgs = []) - { - $request = new ListSinksRequest(); - $request->setParent($parent); - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - - $mergedSettings = $this->defaultCallSettings['listSinks']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->configServiceV2Stub, - 'ListSinks', - $mergedSettings, - $this->descriptors['listSinks'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets a sink. - * - * Sample code: - * ``` - * try { - * $configServiceV2Client = new ConfigServiceV2Client(); - * $formattedSinkName = ConfigServiceV2Client::formatSinkName("[PROJECT]", "[SINK]"); - * $response = $configServiceV2Client->getSink($formattedSinkName); - * } finally { - * $configServiceV2Client->close(); - * } - * ``` - * - * @param string $sinkName Required. The resource name of the sink: - * - * "projects/[PROJECT_ID]/sinks/[SINK_ID]" - * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - * "folders/[FOLDER_ID]/sinks/[SINK_ID]" - * - * Example: `"projects/my-project-id/sinks/my-sink-id"`. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Logging\V2\LogSink - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getSink($sinkName, $optionalArgs = []) - { - $request = new GetSinkRequest(); - $request->setSinkName($sinkName); - - $mergedSettings = $this->defaultCallSettings['getSink']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->configServiceV2Stub, - 'GetSink', - $mergedSettings, - $this->descriptors['getSink'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Creates a sink that exports specified log entries to a destination. The - * export of newly-ingested log entries begins immediately, unless the current - * time is outside the sink's start and end times or the sink's - * `writer_identity` is not permitted to write to the destination. A sink can - * export log entries only from the resource owning the sink. - * - * Sample code: - * ``` - * try { - * $configServiceV2Client = new ConfigServiceV2Client(); - * $formattedParent = ConfigServiceV2Client::formatProjectName("[PROJECT]"); - * $sink = new LogSink(); - * $response = $configServiceV2Client->createSink($formattedParent, $sink); - * } finally { - * $configServiceV2Client->close(); - * } - * ``` - * - * @param string $parent Required. The resource in which to create the sink: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * - * Examples: `"projects/my-logging-project"`, `"organizations/123456789"`. - * @param LogSink $sink Required. The new sink, whose `name` parameter is a sink identifier that - * is not already in use. - * @param array $optionalArgs { - * Optional. - * - * @type bool $uniqueWriterIdentity - * Optional. Determines the kind of IAM identity returned as `writer_identity` - * in the new sink. If this value is omitted or set to false, and if the - * sink's parent is a project, then the value returned as `writer_identity` is - * the same group or service account used by Stackdriver Logging before the - * addition of writer identities to this API. The sink's destination must be - * in the same project as the sink itself. - * - * If this field is set to true, or if the sink is owned by a non-project - * resource such as an organization, then the value of `writer_identity` will - * be a unique service account used only for exports from the new sink. For - * more information, see `writer_identity` in [LogSink][google.logging.v2.LogSink]. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Logging\V2\LogSink - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createSink($parent, $sink, $optionalArgs = []) - { - $request = new CreateSinkRequest(); - $request->setParent($parent); - $request->setSink($sink); - if (isset($optionalArgs['uniqueWriterIdentity'])) { - $request->setUniqueWriterIdentity($optionalArgs['uniqueWriterIdentity']); - } - - $mergedSettings = $this->defaultCallSettings['createSink']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->configServiceV2Stub, - 'CreateSink', - $mergedSettings, - $this->descriptors['createSink'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Updates a sink. If the named sink doesn't exist, then this method is - * identical to - * [sinks.create](https://cloud.google.com/logging/docs/api/reference/rest/v2/projects.sinks/create). - * If the named sink does exist, then this method replaces the following - * fields in the existing sink with values from the new sink: `destination`, - * `filter`, `output_version_format`, `start_time`, and `end_time`. - * The updated filter might also have a new `writer_identity`; see the - * `unique_writer_identity` field. - * - * Sample code: - * ``` - * try { - * $configServiceV2Client = new ConfigServiceV2Client(); - * $formattedSinkName = ConfigServiceV2Client::formatSinkName("[PROJECT]", "[SINK]"); - * $sink = new LogSink(); - * $response = $configServiceV2Client->updateSink($formattedSinkName, $sink); - * } finally { - * $configServiceV2Client->close(); - * } - * ``` - * - * @param string $sinkName Required. The full resource name of the sink to update, including the - * parent resource and the sink identifier: - * - * "projects/[PROJECT_ID]/sinks/[SINK_ID]" - * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - * "folders/[FOLDER_ID]/sinks/[SINK_ID]" - * - * Example: `"projects/my-project-id/sinks/my-sink-id"`. - * @param LogSink $sink Required. The updated sink, whose name is the same identifier that appears - * as part of `sink_name`. If `sink_name` does not exist, then - * this method creates a new sink. - * @param array $optionalArgs { - * Optional. - * - * @type bool $uniqueWriterIdentity - * Optional. See - * [sinks.create](https://cloud.google.com/logging/docs/api/reference/rest/v2/projects.sinks/create) - * for a description of this field. When updating a sink, the effect of this - * field on the value of `writer_identity` in the updated sink depends on both - * the old and new values of this field: - * - * + If the old and new values of this field are both false or both true, - * then there is no change to the sink's `writer_identity`. - * + If the old value is false and the new value is true, then - * `writer_identity` is changed to a unique service account. - * + It is an error if the old value is true and the new value is false. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Logging\V2\LogSink - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function updateSink($sinkName, $sink, $optionalArgs = []) - { - $request = new UpdateSinkRequest(); - $request->setSinkName($sinkName); - $request->setSink($sink); - if (isset($optionalArgs['uniqueWriterIdentity'])) { - $request->setUniqueWriterIdentity($optionalArgs['uniqueWriterIdentity']); - } - - $mergedSettings = $this->defaultCallSettings['updateSink']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->configServiceV2Stub, - 'UpdateSink', - $mergedSettings, - $this->descriptors['updateSink'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Deletes a sink. If the sink has a unique `writer_identity`, then that - * service account is also deleted. - * - * Sample code: - * ``` - * try { - * $configServiceV2Client = new ConfigServiceV2Client(); - * $formattedSinkName = ConfigServiceV2Client::formatSinkName("[PROJECT]", "[SINK]"); - * $configServiceV2Client->deleteSink($formattedSinkName); - * } finally { - * $configServiceV2Client->close(); - * } - * ``` - * - * @param string $sinkName Required. The full resource name of the sink to delete, including the - * parent resource and the sink identifier: - * - * "projects/[PROJECT_ID]/sinks/[SINK_ID]" - * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - * "folders/[FOLDER_ID]/sinks/[SINK_ID]" - * - * Example: `"projects/my-project-id/sinks/my-sink-id"`. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function deleteSink($sinkName, $optionalArgs = []) - { - $request = new DeleteSinkRequest(); - $request->setSinkName($sinkName); - - $mergedSettings = $this->defaultCallSettings['deleteSink']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->configServiceV2Stub, - 'DeleteSink', - $mergedSettings, - $this->descriptors['deleteSink'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->configServiceV2Stub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see ConfigServiceV2ClientImpl} class. } diff --git a/src/Logging/V2/Gapic/ConfigServiceV2GapicClient.php b/src/Logging/V2/Gapic/ConfigServiceV2GapicClient.php new file mode 100644 index 000000000000..37fae77189a6 --- /dev/null +++ b/src/Logging/V2/Gapic/ConfigServiceV2GapicClient.php @@ -0,0 +1,738 @@ +listSinks($formattedParent); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $configServiceV2Client->listSinks($formattedParent, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $configServiceV2Client->close(); + * } + * ``` + * + * Many parameters require resource names to be formatted in a particular way. To assist + * with these names, this class includes a format method for each type of name, and additionally + * a parse method to extract the individual identifiers contained within names that are + * returned. + * + * @experimental + */ +class ConfigServiceV2GapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'logging.googleapis.com'; + + /** + * The default port of the service. + */ + const DEFAULT_SERVICE_PORT = 443; + + /** + * The default timeout for non-retrying methods. + */ + const DEFAULT_TIMEOUT_MILLIS = 30000; + + /** + * The name of the code generator, to be included in the agent header. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $projectNameTemplate; + private static $sinkNameTemplate; + + protected $grpcCredentialsHelper; + protected $configServiceV2Stub; + private $scopes; + private $defaultCallSettings; + private $descriptors; + + /** + * Formats a string containing the fully-qualified path to represent + * a project resource. + * + * @param string $project + * + * @return string The formatted project resource. + * @experimental + */ + public static function formatProjectName($project) + { + return self::getProjectNameTemplate()->render([ + 'project' => $project, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a sink resource. + * + * @param string $project + * @param string $sink + * + * @return string The formatted sink resource. + * @experimental + */ + public static function formatSinkName($project, $sink) + { + return self::getSinkNameTemplate()->render([ + 'project' => $project, + 'sink' => $sink, + ]); + } + + /** + * Parses the project from the given fully-qualified path which + * represents a project resource. + * + * @param string $projectName The fully-qualified project resource. + * + * @return string The extracted project value. + * @experimental + */ + public static function parseProjectFromProjectName($projectName) + { + return self::getProjectNameTemplate()->match($projectName)['project']; + } + + /** + * Parses the project from the given fully-qualified path which + * represents a sink resource. + * + * @param string $sinkName The fully-qualified sink resource. + * + * @return string The extracted project value. + * @experimental + */ + public static function parseProjectFromSinkName($sinkName) + { + return self::getSinkNameTemplate()->match($sinkName)['project']; + } + + /** + * Parses the sink from the given fully-qualified path which + * represents a sink resource. + * + * @param string $sinkName The fully-qualified sink resource. + * + * @return string The extracted sink value. + * @experimental + */ + public static function parseSinkFromSinkName($sinkName) + { + return self::getSinkNameTemplate()->match($sinkName)['sink']; + } + + private static function getProjectNameTemplate() + { + if (self::$projectNameTemplate == null) { + self::$projectNameTemplate = new PathTemplate('projects/{project}'); + } + + return self::$projectNameTemplate; + } + + private static function getSinkNameTemplate() + { + if (self::$sinkNameTemplate == null) { + self::$sinkNameTemplate = new PathTemplate('projects/{project}/sinks/{sink}'); + } + + return self::$sinkNameTemplate; + } + + private static function getPageStreamingDescriptors() + { + $listSinksPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getSinks', + ]); + + $pageStreamingDescriptors = [ + 'listSinks' => $listSinksPageStreamingDescriptor, + ]; + + return $pageStreamingDescriptors; + } + + private static function getGapicVersion() + { + if (file_exists(__DIR__.'/../VERSION')) { + return trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { + return \Google\Cloud\ServiceBuilder::VERSION; + } else { + return; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'logging.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * A CredentialsLoader object created using the Google\Auth library. + * @type array $scopes A string array of scopes to use when acquiring credentials. + * Defaults to the scopes for the Stackdriver Logging API. + * @type array $retryingOverride + * An associative array of string => RetryOptions, where the keys + * are method names (e.g. 'createFoo'), that overrides default retrying + * settings. A value of null indicates that the method in question should + * not retry. + * @type int $timeoutMillis The timeout in milliseconds to use for calls + * that don't use retries. For calls that use retries, + * set the timeout in RetryOptions. + * Default: 30000 (30 seconds) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + 'https://www.googleapis.com/auth/logging.admin', + 'https://www.googleapis.com/auth/logging.read', + 'https://www.googleapis.com/auth/logging.write', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'listSinks' => $defaultDescriptors, + 'getSink' => $defaultDescriptors, + 'createSink' => $defaultDescriptors, + 'updateSink' => $defaultDescriptors, + 'deleteSink' => $defaultDescriptors, + ]; + $pageStreamingDescriptors = self::getPageStreamingDescriptors(); + foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { + $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/config_service_v2_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.logging.v2.ConfigServiceV2', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createConfigServiceV2StubFunction = function ($hostname, $opts, $channel) { + return new ConfigServiceV2GrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createConfigServiceV2StubFunction', $options)) { + $createConfigServiceV2StubFunction = $options['createConfigServiceV2StubFunction']; + } + $this->configServiceV2Stub = $this->grpcCredentialsHelper->createStub($createConfigServiceV2StubFunction); + } + + /** + * Lists sinks. + * + * Sample code: + * ``` + * try { + * $configServiceV2Client = new ConfigServiceV2Client(); + * $formattedParent = ConfigServiceV2Client::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $configServiceV2Client->listSinks($formattedParent); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $configServiceV2Client->listSinks($formattedParent, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $configServiceV2Client->close(); + * } + * ``` + * + * @param string $parent Required. The parent resource whose sinks are to be listed: + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @param array $optionalArgs { + * Optional. + * + * @type string $pageToken + * A page token is used to specify a page of values to be returned. + * If no page token is specified (the default), the first page + * of values will be returned. Any page token used here must have + * been generated by a previous call to the API. + * @type int $pageSize + * The maximum number of resources contained in the underlying API + * response. The API may return fewer values in a page, even if + * there are additional values to be retrieved. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listSinks($parent, $optionalArgs = []) + { + $request = new ListSinksRequest(); + $request->setParent($parent); + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + + $mergedSettings = $this->defaultCallSettings['listSinks']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->configServiceV2Stub, + 'ListSinks', + $mergedSettings, + $this->descriptors['listSinks'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets a sink. + * + * Sample code: + * ``` + * try { + * $configServiceV2Client = new ConfigServiceV2Client(); + * $formattedSinkName = ConfigServiceV2Client::formatSinkName("[PROJECT]", "[SINK]"); + * $response = $configServiceV2Client->getSink($formattedSinkName); + * } finally { + * $configServiceV2Client->close(); + * } + * ``` + * + * @param string $sinkName Required. The resource name of the sink: + * + * "projects/[PROJECT_ID]/sinks/[SINK_ID]" + * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" + * + * Example: `"projects/my-project-id/sinks/my-sink-id"`. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Logging\V2\LogSink + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getSink($sinkName, $optionalArgs = []) + { + $request = new GetSinkRequest(); + $request->setSinkName($sinkName); + + $mergedSettings = $this->defaultCallSettings['getSink']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->configServiceV2Stub, + 'GetSink', + $mergedSettings, + $this->descriptors['getSink'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Creates a sink that exports specified log entries to a destination. The + * export of newly-ingested log entries begins immediately, unless the current + * time is outside the sink's start and end times or the sink's + * `writer_identity` is not permitted to write to the destination. A sink can + * export log entries only from the resource owning the sink. + * + * Sample code: + * ``` + * try { + * $configServiceV2Client = new ConfigServiceV2Client(); + * $formattedParent = ConfigServiceV2Client::formatProjectName("[PROJECT]"); + * $sink = new LogSink(); + * $response = $configServiceV2Client->createSink($formattedParent, $sink); + * } finally { + * $configServiceV2Client->close(); + * } + * ``` + * + * @param string $parent Required. The resource in which to create the sink: + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * + * Examples: `"projects/my-logging-project"`, `"organizations/123456789"`. + * @param LogSink $sink Required. The new sink, whose `name` parameter is a sink identifier that + * is not already in use. + * @param array $optionalArgs { + * Optional. + * + * @type bool $uniqueWriterIdentity + * Optional. Determines the kind of IAM identity returned as `writer_identity` + * in the new sink. If this value is omitted or set to false, and if the + * sink's parent is a project, then the value returned as `writer_identity` is + * the same group or service account used by Stackdriver Logging before the + * addition of writer identities to this API. The sink's destination must be + * in the same project as the sink itself. + * + * If this field is set to true, or if the sink is owned by a non-project + * resource such as an organization, then the value of `writer_identity` will + * be a unique service account used only for exports from the new sink. For + * more information, see `writer_identity` in [LogSink][google.logging.v2.LogSink]. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Logging\V2\LogSink + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createSink($parent, $sink, $optionalArgs = []) + { + $request = new CreateSinkRequest(); + $request->setParent($parent); + $request->setSink($sink); + if (isset($optionalArgs['uniqueWriterIdentity'])) { + $request->setUniqueWriterIdentity($optionalArgs['uniqueWriterIdentity']); + } + + $mergedSettings = $this->defaultCallSettings['createSink']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->configServiceV2Stub, + 'CreateSink', + $mergedSettings, + $this->descriptors['createSink'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Updates a sink. If the named sink doesn't exist, then this method is + * identical to + * [sinks.create](https://cloud.google.com/logging/docs/api/reference/rest/v2/projects.sinks/create). + * If the named sink does exist, then this method replaces the following + * fields in the existing sink with values from the new sink: `destination`, + * `filter`, `output_version_format`, `start_time`, and `end_time`. + * The updated filter might also have a new `writer_identity`; see the + * `unique_writer_identity` field. + * + * Sample code: + * ``` + * try { + * $configServiceV2Client = new ConfigServiceV2Client(); + * $formattedSinkName = ConfigServiceV2Client::formatSinkName("[PROJECT]", "[SINK]"); + * $sink = new LogSink(); + * $response = $configServiceV2Client->updateSink($formattedSinkName, $sink); + * } finally { + * $configServiceV2Client->close(); + * } + * ``` + * + * @param string $sinkName Required. The full resource name of the sink to update, including the + * parent resource and the sink identifier: + * + * "projects/[PROJECT_ID]/sinks/[SINK_ID]" + * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" + * + * Example: `"projects/my-project-id/sinks/my-sink-id"`. + * @param LogSink $sink Required. The updated sink, whose name is the same identifier that appears + * as part of `sink_name`. If `sink_name` does not exist, then + * this method creates a new sink. + * @param array $optionalArgs { + * Optional. + * + * @type bool $uniqueWriterIdentity + * Optional. See + * [sinks.create](https://cloud.google.com/logging/docs/api/reference/rest/v2/projects.sinks/create) + * for a description of this field. When updating a sink, the effect of this + * field on the value of `writer_identity` in the updated sink depends on both + * the old and new values of this field: + * + * + If the old and new values of this field are both false or both true, + * then there is no change to the sink's `writer_identity`. + * + If the old value is false and the new value is true, then + * `writer_identity` is changed to a unique service account. + * + It is an error if the old value is true and the new value is false. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Logging\V2\LogSink + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function updateSink($sinkName, $sink, $optionalArgs = []) + { + $request = new UpdateSinkRequest(); + $request->setSinkName($sinkName); + $request->setSink($sink); + if (isset($optionalArgs['uniqueWriterIdentity'])) { + $request->setUniqueWriterIdentity($optionalArgs['uniqueWriterIdentity']); + } + + $mergedSettings = $this->defaultCallSettings['updateSink']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->configServiceV2Stub, + 'UpdateSink', + $mergedSettings, + $this->descriptors['updateSink'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Deletes a sink. If the sink has a unique `writer_identity`, then that + * service account is also deleted. + * + * Sample code: + * ``` + * try { + * $configServiceV2Client = new ConfigServiceV2Client(); + * $formattedSinkName = ConfigServiceV2Client::formatSinkName("[PROJECT]", "[SINK]"); + * $configServiceV2Client->deleteSink($formattedSinkName); + * } finally { + * $configServiceV2Client->close(); + * } + * ``` + * + * @param string $sinkName Required. The full resource name of the sink to delete, including the + * parent resource and the sink identifier: + * + * "projects/[PROJECT_ID]/sinks/[SINK_ID]" + * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + * "folders/[FOLDER_ID]/sinks/[SINK_ID]" + * + * Example: `"projects/my-project-id/sinks/my-sink-id"`. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function deleteSink($sinkName, $optionalArgs = []) + { + $request = new DeleteSinkRequest(); + $request->setSinkName($sinkName); + + $mergedSettings = $this->defaultCallSettings['deleteSink']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->configServiceV2Stub, + 'DeleteSink', + $mergedSettings, + $this->descriptors['deleteSink'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->configServiceV2Stub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/Logging/V2/Gapic/LoggingServiceV2GapicClient.php b/src/Logging/V2/Gapic/LoggingServiceV2GapicClient.php new file mode 100644 index 000000000000..3ca10519b2fa --- /dev/null +++ b/src/Logging/V2/Gapic/LoggingServiceV2GapicClient.php @@ -0,0 +1,833 @@ +deleteLog($formattedLogName); + * } finally { + * $loggingServiceV2Client->close(); + * } + * ``` + * + * Many parameters require resource names to be formatted in a particular way. To assist + * with these names, this class includes a format method for each type of name, and additionally + * a parse method to extract the individual identifiers contained within names that are + * returned. + * + * @experimental + */ +class LoggingServiceV2GapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'logging.googleapis.com'; + + /** + * The default port of the service. + */ + const DEFAULT_SERVICE_PORT = 443; + + /** + * The default timeout for non-retrying methods. + */ + const DEFAULT_TIMEOUT_MILLIS = 30000; + + /** + * The name of the code generator, to be included in the agent header. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $projectNameTemplate; + private static $logNameTemplate; + + protected $grpcCredentialsHelper; + protected $loggingServiceV2Stub; + private $scopes; + private $defaultCallSettings; + private $descriptors; + + /** + * Formats a string containing the fully-qualified path to represent + * a project resource. + * + * @param string $project + * + * @return string The formatted project resource. + * @experimental + */ + public static function formatProjectName($project) + { + return self::getProjectNameTemplate()->render([ + 'project' => $project, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a log resource. + * + * @param string $project + * @param string $log + * + * @return string The formatted log resource. + * @experimental + */ + public static function formatLogName($project, $log) + { + return self::getLogNameTemplate()->render([ + 'project' => $project, + 'log' => $log, + ]); + } + + /** + * Parses the project from the given fully-qualified path which + * represents a project resource. + * + * @param string $projectName The fully-qualified project resource. + * + * @return string The extracted project value. + * @experimental + */ + public static function parseProjectFromProjectName($projectName) + { + return self::getProjectNameTemplate()->match($projectName)['project']; + } + + /** + * Parses the project from the given fully-qualified path which + * represents a log resource. + * + * @param string $logName The fully-qualified log resource. + * + * @return string The extracted project value. + * @experimental + */ + public static function parseProjectFromLogName($logName) + { + return self::getLogNameTemplate()->match($logName)['project']; + } + + /** + * Parses the log from the given fully-qualified path which + * represents a log resource. + * + * @param string $logName The fully-qualified log resource. + * + * @return string The extracted log value. + * @experimental + */ + public static function parseLogFromLogName($logName) + { + return self::getLogNameTemplate()->match($logName)['log']; + } + + private static function getProjectNameTemplate() + { + if (self::$projectNameTemplate == null) { + self::$projectNameTemplate = new PathTemplate('projects/{project}'); + } + + return self::$projectNameTemplate; + } + + private static function getLogNameTemplate() + { + if (self::$logNameTemplate == null) { + self::$logNameTemplate = new PathTemplate('projects/{project}/logs/{log}'); + } + + return self::$logNameTemplate; + } + + private static function getPageStreamingDescriptors() + { + $listLogEntriesPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getEntries', + ]); + $listMonitoredResourceDescriptorsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getResourceDescriptors', + ]); + $listLogsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getLogNames', + ]); + + $pageStreamingDescriptors = [ + 'listLogEntries' => $listLogEntriesPageStreamingDescriptor, + 'listMonitoredResourceDescriptors' => $listMonitoredResourceDescriptorsPageStreamingDescriptor, + 'listLogs' => $listLogsPageStreamingDescriptor, + ]; + + return $pageStreamingDescriptors; + } + + private static function getGapicVersion() + { + if (file_exists(__DIR__.'/../VERSION')) { + return trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { + return \Google\Cloud\ServiceBuilder::VERSION; + } else { + return; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'logging.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * A CredentialsLoader object created using the Google\Auth library. + * @type array $scopes A string array of scopes to use when acquiring credentials. + * Defaults to the scopes for the Stackdriver Logging API. + * @type array $retryingOverride + * An associative array of string => RetryOptions, where the keys + * are method names (e.g. 'createFoo'), that overrides default retrying + * settings. A value of null indicates that the method in question should + * not retry. + * @type int $timeoutMillis The timeout in milliseconds to use for calls + * that don't use retries. For calls that use retries, + * set the timeout in RetryOptions. + * Default: 30000 (30 seconds) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + 'https://www.googleapis.com/auth/logging.admin', + 'https://www.googleapis.com/auth/logging.read', + 'https://www.googleapis.com/auth/logging.write', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'deleteLog' => $defaultDescriptors, + 'writeLogEntries' => $defaultDescriptors, + 'listLogEntries' => $defaultDescriptors, + 'listMonitoredResourceDescriptors' => $defaultDescriptors, + 'listLogs' => $defaultDescriptors, + ]; + $pageStreamingDescriptors = self::getPageStreamingDescriptors(); + foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { + $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/logging_service_v2_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.logging.v2.LoggingServiceV2', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createLoggingServiceV2StubFunction = function ($hostname, $opts, $channel) { + return new LoggingServiceV2GrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createLoggingServiceV2StubFunction', $options)) { + $createLoggingServiceV2StubFunction = $options['createLoggingServiceV2StubFunction']; + } + $this->loggingServiceV2Stub = $this->grpcCredentialsHelper->createStub($createLoggingServiceV2StubFunction); + } + + /** + * Deletes all the log entries in a log. + * The log reappears if it receives new entries. + * Log entries written shortly before the delete operation might not be + * deleted. + * + * Sample code: + * ``` + * try { + * $loggingServiceV2Client = new LoggingServiceV2Client(); + * $formattedLogName = LoggingServiceV2Client::formatLogName("[PROJECT]", "[LOG]"); + * $loggingServiceV2Client->deleteLog($formattedLogName); + * } finally { + * $loggingServiceV2Client->close(); + * } + * ``` + * + * @param string $logName Required. The resource name of the log to delete: + * + * "projects/[PROJECT_ID]/logs/[LOG_ID]" + * "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" + * "folders/[FOLDER_ID]/logs/[LOG_ID]" + * + * `[LOG_ID]` must be URL-encoded. For example, + * `"projects/my-project-id/logs/syslog"`, + * `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`. + * For more information about log names, see + * [LogEntry][google.logging.v2.LogEntry]. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function deleteLog($logName, $optionalArgs = []) + { + $request = new DeleteLogRequest(); + $request->setLogName($logName); + + $mergedSettings = $this->defaultCallSettings['deleteLog']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->loggingServiceV2Stub, + 'DeleteLog', + $mergedSettings, + $this->descriptors['deleteLog'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Writes log entries to Stackdriver Logging. + * + * Sample code: + * ``` + * try { + * $loggingServiceV2Client = new LoggingServiceV2Client(); + * $entries = []; + * $response = $loggingServiceV2Client->writeLogEntries($entries); + * } finally { + * $loggingServiceV2Client->close(); + * } + * ``` + * + * @param LogEntry[] $entries Required. The log entries to write. Values supplied for the fields + * `log_name`, `resource`, and `labels` in this `entries.write` request are + * inserted into those log entries in this list that do not provide their own + * values. + * + * Stackdriver Logging also creates and inserts values for `timestamp` and + * `insert_id` if the entries do not provide them. The created `insert_id` for + * the N'th entry in this list will be greater than earlier entries and less + * than later entries. Otherwise, the order of log entries in this list does + * not matter. + * + * To improve throughput and to avoid exceeding the + * [quota limit](https://cloud.google.com/logging/quota-policy) for calls to `entries.write`, + * you should write multiple log entries at once rather than + * calling this method for each individual log entry. + * @param array $optionalArgs { + * Optional. + * + * @type string $logName + * Optional. A default log resource name that is assigned to all log entries + * in `entries` that do not specify a value for `log_name`: + * + * "projects/[PROJECT_ID]/logs/[LOG_ID]" + * "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" + * "folders/[FOLDER_ID]/logs/[LOG_ID]" + * + * `[LOG_ID]` must be URL-encoded. For example, + * `"projects/my-project-id/logs/syslog"` or + * `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`. + * For more information about log names, see + * [LogEntry][google.logging.v2.LogEntry]. + * @type MonitoredResource $resource + * Optional. A default monitored resource object that is assigned to all log + * entries in `entries` that do not specify a value for `resource`. Example: + * + * { "type": "gce_instance", + * "labels": { + * "zone": "us-central1-a", "instance_id": "00000000000000000000" }} + * + * See [LogEntry][google.logging.v2.LogEntry]. + * @type array $labels + * Optional. Default labels that are added to the `labels` field of all log + * entries in `entries`. If a log entry already has a label with the same key + * as a label in this parameter, then the log entry's label is not changed. + * See [LogEntry][google.logging.v2.LogEntry]. + * @type bool $partialSuccess + * Optional. Whether valid entries should be written even if some other + * entries fail due to INVALID_ARGUMENT or PERMISSION_DENIED errors. If any + * entry is not written, then the response status is the error associated + * with one of the failed entries and the response includes error details + * keyed by the entries' zero-based index in the `entries.write` method. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Logging\V2\WriteLogEntriesResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function writeLogEntries($entries, $optionalArgs = []) + { + $request = new WriteLogEntriesRequest(); + $request->setEntries($entries); + if (isset($optionalArgs['logName'])) { + $request->setLogName($optionalArgs['logName']); + } + if (isset($optionalArgs['resource'])) { + $request->setResource($optionalArgs['resource']); + } + if (isset($optionalArgs['labels'])) { + $request->setLabels($optionalArgs['labels']); + } + if (isset($optionalArgs['partialSuccess'])) { + $request->setPartialSuccess($optionalArgs['partialSuccess']); + } + + $mergedSettings = $this->defaultCallSettings['writeLogEntries']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->loggingServiceV2Stub, + 'WriteLogEntries', + $mergedSettings, + $this->descriptors['writeLogEntries'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists log entries. Use this method to retrieve log entries from + * Stackdriver Logging. For ways to export log entries, see + * [Exporting Logs](https://cloud.google.com/logging/docs/export). + * + * Sample code: + * ``` + * try { + * $loggingServiceV2Client = new LoggingServiceV2Client(); + * $resourceNames = []; + * // Iterate through all elements + * $pagedResponse = $loggingServiceV2Client->listLogEntries($resourceNames); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $loggingServiceV2Client->listLogEntries($resourceNames, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $loggingServiceV2Client->close(); + * } + * ``` + * + * @param string[] $resourceNames Required. Names of one or more parent resources from which to + * retrieve log entries: + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * + * Projects listed in the `project_ids` field are added to this list. + * @param array $optionalArgs { + * Optional. + * + * @type string[] $projectIds + * Deprecated. Use `resource_names` instead. One or more project identifiers + * or project numbers from which to retrieve log entries. Example: + * `"my-project-1A"`. If present, these project identifiers are converted to + * resource name format and added to the list of resources in + * `resource_names`. + * @type string $filter + * Optional. A filter that chooses which log entries to return. See [Advanced + * Logs Filters](https://cloud.google.com/logging/docs/view/advanced_filters). Only log entries that + * match the filter are returned. An empty filter matches all log entries in + * the resources listed in `resource_names`. Referencing a parent resource + * that is not listed in `resource_names` will cause the filter to return no + * results. + * The maximum length of the filter is 20000 characters. + * @type string $orderBy + * Optional. How the results should be sorted. Presently, the only permitted + * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first + * option returns entries in order of increasing values of + * `LogEntry.timestamp` (oldest first), and the second option returns entries + * in order of decreasing timestamps (newest first). Entries with equal + * timestamps are returned in order of their `insert_id` values. + * @type int $pageSize + * The maximum number of resources contained in the underlying API + * response. The API may return fewer values in a page, even if + * there are additional values to be retrieved. + * @type string $pageToken + * A page token is used to specify a page of values to be returned. + * If no page token is specified (the default), the first page + * of values will be returned. Any page token used here must have + * been generated by a previous call to the API. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listLogEntries($resourceNames, $optionalArgs = []) + { + $request = new ListLogEntriesRequest(); + $request->setResourceNames($resourceNames); + if (isset($optionalArgs['projectIds'])) { + $request->setProjectIds($optionalArgs['projectIds']); + } + if (isset($optionalArgs['filter'])) { + $request->setFilter($optionalArgs['filter']); + } + if (isset($optionalArgs['orderBy'])) { + $request->setOrderBy($optionalArgs['orderBy']); + } + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listLogEntries']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->loggingServiceV2Stub, + 'ListLogEntries', + $mergedSettings, + $this->descriptors['listLogEntries'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists the descriptors for monitored resource types used by Stackdriver + * Logging. + * + * Sample code: + * ``` + * try { + * $loggingServiceV2Client = new LoggingServiceV2Client(); + * + * // Iterate through all elements + * $pagedResponse = $loggingServiceV2Client->listMonitoredResourceDescriptors(); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $loggingServiceV2Client->listMonitoredResourceDescriptors(['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $loggingServiceV2Client->close(); + * } + * ``` + * + * @param array $optionalArgs { + * Optional. + * + * @type int $pageSize + * The maximum number of resources contained in the underlying API + * response. The API may return fewer values in a page, even if + * there are additional values to be retrieved. + * @type string $pageToken + * A page token is used to specify a page of values to be returned. + * If no page token is specified (the default), the first page + * of values will be returned. Any page token used here must have + * been generated by a previous call to the API. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listMonitoredResourceDescriptors($optionalArgs = []) + { + $request = new ListMonitoredResourceDescriptorsRequest(); + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listMonitoredResourceDescriptors']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->loggingServiceV2Stub, + 'ListMonitoredResourceDescriptors', + $mergedSettings, + $this->descriptors['listMonitoredResourceDescriptors'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists the logs in projects, organizations, folders, or billing accounts. + * Only logs that have entries are listed. + * + * Sample code: + * ``` + * try { + * $loggingServiceV2Client = new LoggingServiceV2Client(); + * $formattedParent = LoggingServiceV2Client::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $loggingServiceV2Client->listLogs($formattedParent); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $loggingServiceV2Client->listLogs($formattedParent, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $loggingServiceV2Client->close(); + * } + * ``` + * + * @param string $parent Required. The resource name that owns the logs: + * + * "projects/[PROJECT_ID]" + * "organizations/[ORGANIZATION_ID]" + * "billingAccounts/[BILLING_ACCOUNT_ID]" + * "folders/[FOLDER_ID]" + * @param array $optionalArgs { + * Optional. + * + * @type int $pageSize + * The maximum number of resources contained in the underlying API + * response. The API may return fewer values in a page, even if + * there are additional values to be retrieved. + * @type string $pageToken + * A page token is used to specify a page of values to be returned. + * If no page token is specified (the default), the first page + * of values will be returned. Any page token used here must have + * been generated by a previous call to the API. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listLogs($parent, $optionalArgs = []) + { + $request = new ListLogsRequest(); + $request->setParent($parent); + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listLogs']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->loggingServiceV2Stub, + 'ListLogs', + $mergedSettings, + $this->descriptors['listLogs'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->loggingServiceV2Stub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/Logging/V2/Gapic/MetricsServiceV2GapicClient.php b/src/Logging/V2/Gapic/MetricsServiceV2GapicClient.php new file mode 100644 index 000000000000..f60547ee7165 --- /dev/null +++ b/src/Logging/V2/Gapic/MetricsServiceV2GapicClient.php @@ -0,0 +1,674 @@ +listLogMetrics($formattedParent); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $metricsServiceV2Client->listLogMetrics($formattedParent, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $metricsServiceV2Client->close(); + * } + * ``` + * + * Many parameters require resource names to be formatted in a particular way. To assist + * with these names, this class includes a format method for each type of name, and additionally + * a parse method to extract the individual identifiers contained within names that are + * returned. + * + * @experimental + */ +class MetricsServiceV2GapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'logging.googleapis.com'; + + /** + * The default port of the service. + */ + const DEFAULT_SERVICE_PORT = 443; + + /** + * The default timeout for non-retrying methods. + */ + const DEFAULT_TIMEOUT_MILLIS = 30000; + + /** + * The name of the code generator, to be included in the agent header. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $projectNameTemplate; + private static $metricNameTemplate; + + protected $grpcCredentialsHelper; + protected $metricsServiceV2Stub; + private $scopes; + private $defaultCallSettings; + private $descriptors; + + /** + * Formats a string containing the fully-qualified path to represent + * a project resource. + * + * @param string $project + * + * @return string The formatted project resource. + * @experimental + */ + public static function formatProjectName($project) + { + return self::getProjectNameTemplate()->render([ + 'project' => $project, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a metric resource. + * + * @param string $project + * @param string $metric + * + * @return string The formatted metric resource. + * @experimental + */ + public static function formatMetricName($project, $metric) + { + return self::getMetricNameTemplate()->render([ + 'project' => $project, + 'metric' => $metric, + ]); + } + + /** + * Parses the project from the given fully-qualified path which + * represents a project resource. + * + * @param string $projectName The fully-qualified project resource. + * + * @return string The extracted project value. + * @experimental + */ + public static function parseProjectFromProjectName($projectName) + { + return self::getProjectNameTemplate()->match($projectName)['project']; + } + + /** + * Parses the project from the given fully-qualified path which + * represents a metric resource. + * + * @param string $metricName The fully-qualified metric resource. + * + * @return string The extracted project value. + * @experimental + */ + public static function parseProjectFromMetricName($metricName) + { + return self::getMetricNameTemplate()->match($metricName)['project']; + } + + /** + * Parses the metric from the given fully-qualified path which + * represents a metric resource. + * + * @param string $metricName The fully-qualified metric resource. + * + * @return string The extracted metric value. + * @experimental + */ + public static function parseMetricFromMetricName($metricName) + { + return self::getMetricNameTemplate()->match($metricName)['metric']; + } + + private static function getProjectNameTemplate() + { + if (self::$projectNameTemplate == null) { + self::$projectNameTemplate = new PathTemplate('projects/{project}'); + } + + return self::$projectNameTemplate; + } + + private static function getMetricNameTemplate() + { + if (self::$metricNameTemplate == null) { + self::$metricNameTemplate = new PathTemplate('projects/{project}/metrics/{metric}'); + } + + return self::$metricNameTemplate; + } + + private static function getPageStreamingDescriptors() + { + $listLogMetricsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getMetrics', + ]); + + $pageStreamingDescriptors = [ + 'listLogMetrics' => $listLogMetricsPageStreamingDescriptor, + ]; + + return $pageStreamingDescriptors; + } + + private static function getGapicVersion() + { + if (file_exists(__DIR__.'/../VERSION')) { + return trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { + return \Google\Cloud\ServiceBuilder::VERSION; + } else { + return; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'logging.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * A CredentialsLoader object created using the Google\Auth library. + * @type array $scopes A string array of scopes to use when acquiring credentials. + * Defaults to the scopes for the Stackdriver Logging API. + * @type array $retryingOverride + * An associative array of string => RetryOptions, where the keys + * are method names (e.g. 'createFoo'), that overrides default retrying + * settings. A value of null indicates that the method in question should + * not retry. + * @type int $timeoutMillis The timeout in milliseconds to use for calls + * that don't use retries. For calls that use retries, + * set the timeout in RetryOptions. + * Default: 30000 (30 seconds) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloud-platform.read-only', + 'https://www.googleapis.com/auth/logging.admin', + 'https://www.googleapis.com/auth/logging.read', + 'https://www.googleapis.com/auth/logging.write', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'listLogMetrics' => $defaultDescriptors, + 'getLogMetric' => $defaultDescriptors, + 'createLogMetric' => $defaultDescriptors, + 'updateLogMetric' => $defaultDescriptors, + 'deleteLogMetric' => $defaultDescriptors, + ]; + $pageStreamingDescriptors = self::getPageStreamingDescriptors(); + foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { + $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/metrics_service_v2_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.logging.v2.MetricsServiceV2', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createMetricsServiceV2StubFunction = function ($hostname, $opts, $channel) { + return new MetricsServiceV2GrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createMetricsServiceV2StubFunction', $options)) { + $createMetricsServiceV2StubFunction = $options['createMetricsServiceV2StubFunction']; + } + $this->metricsServiceV2Stub = $this->grpcCredentialsHelper->createStub($createMetricsServiceV2StubFunction); + } + + /** + * Lists logs-based metrics. + * + * Sample code: + * ``` + * try { + * $metricsServiceV2Client = new MetricsServiceV2Client(); + * $formattedParent = MetricsServiceV2Client::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $metricsServiceV2Client->listLogMetrics($formattedParent); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $metricsServiceV2Client->listLogMetrics($formattedParent, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $metricsServiceV2Client->close(); + * } + * ``` + * + * @param string $parent Required. The name of the project containing the metrics: + * + * "projects/[PROJECT_ID]" + * @param array $optionalArgs { + * Optional. + * + * @type string $pageToken + * A page token is used to specify a page of values to be returned. + * If no page token is specified (the default), the first page + * of values will be returned. Any page token used here must have + * been generated by a previous call to the API. + * @type int $pageSize + * The maximum number of resources contained in the underlying API + * response. The API may return fewer values in a page, even if + * there are additional values to be retrieved. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listLogMetrics($parent, $optionalArgs = []) + { + $request = new ListLogMetricsRequest(); + $request->setParent($parent); + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + + $mergedSettings = $this->defaultCallSettings['listLogMetrics']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricsServiceV2Stub, + 'ListLogMetrics', + $mergedSettings, + $this->descriptors['listLogMetrics'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets a logs-based metric. + * + * Sample code: + * ``` + * try { + * $metricsServiceV2Client = new MetricsServiceV2Client(); + * $formattedMetricName = MetricsServiceV2Client::formatMetricName("[PROJECT]", "[METRIC]"); + * $response = $metricsServiceV2Client->getLogMetric($formattedMetricName); + * } finally { + * $metricsServiceV2Client->close(); + * } + * ``` + * + * @param string $metricName The resource name of the desired metric: + * + * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Logging\V2\LogMetric + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getLogMetric($metricName, $optionalArgs = []) + { + $request = new GetLogMetricRequest(); + $request->setMetricName($metricName); + + $mergedSettings = $this->defaultCallSettings['getLogMetric']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricsServiceV2Stub, + 'GetLogMetric', + $mergedSettings, + $this->descriptors['getLogMetric'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Creates a logs-based metric. + * + * Sample code: + * ``` + * try { + * $metricsServiceV2Client = new MetricsServiceV2Client(); + * $formattedParent = MetricsServiceV2Client::formatProjectName("[PROJECT]"); + * $metric = new LogMetric(); + * $response = $metricsServiceV2Client->createLogMetric($formattedParent, $metric); + * } finally { + * $metricsServiceV2Client->close(); + * } + * ``` + * + * @param string $parent The resource name of the project in which to create the metric: + * + * "projects/[PROJECT_ID]" + * + * The new metric must be provided in the request. + * @param LogMetric $metric The new logs-based metric, which must not have an identifier that + * already exists. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Logging\V2\LogMetric + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createLogMetric($parent, $metric, $optionalArgs = []) + { + $request = new CreateLogMetricRequest(); + $request->setParent($parent); + $request->setMetric($metric); + + $mergedSettings = $this->defaultCallSettings['createLogMetric']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricsServiceV2Stub, + 'CreateLogMetric', + $mergedSettings, + $this->descriptors['createLogMetric'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Creates or updates a logs-based metric. + * + * Sample code: + * ``` + * try { + * $metricsServiceV2Client = new MetricsServiceV2Client(); + * $formattedMetricName = MetricsServiceV2Client::formatMetricName("[PROJECT]", "[METRIC]"); + * $metric = new LogMetric(); + * $response = $metricsServiceV2Client->updateLogMetric($formattedMetricName, $metric); + * } finally { + * $metricsServiceV2Client->close(); + * } + * ``` + * + * @param string $metricName The resource name of the metric to update: + * + * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + * + * The updated metric must be provided in the request and it's + * `name` field must be the same as `[METRIC_ID]` If the metric + * does not exist in `[PROJECT_ID]`, then a new metric is created. + * @param LogMetric $metric The updated metric. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Logging\V2\LogMetric + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function updateLogMetric($metricName, $metric, $optionalArgs = []) + { + $request = new UpdateLogMetricRequest(); + $request->setMetricName($metricName); + $request->setMetric($metric); + + $mergedSettings = $this->defaultCallSettings['updateLogMetric']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricsServiceV2Stub, + 'UpdateLogMetric', + $mergedSettings, + $this->descriptors['updateLogMetric'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Deletes a logs-based metric. + * + * Sample code: + * ``` + * try { + * $metricsServiceV2Client = new MetricsServiceV2Client(); + * $formattedMetricName = MetricsServiceV2Client::formatMetricName("[PROJECT]", "[METRIC]"); + * $metricsServiceV2Client->deleteLogMetric($formattedMetricName); + * } finally { + * $metricsServiceV2Client->close(); + * } + * ``` + * + * @param string $metricName The resource name of the metric to delete: + * + * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function deleteLogMetric($metricName, $optionalArgs = []) + { + $request = new DeleteLogMetricRequest(); + $request->setMetricName($metricName); + + $mergedSettings = $this->defaultCallSettings['deleteLogMetric']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricsServiceV2Stub, + 'DeleteLogMetric', + $mergedSettings, + $this->descriptors['deleteLogMetric'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->metricsServiceV2Stub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/Logging/V2/LoggingServiceV2Client.php b/src/Logging/V2/LoggingServiceV2Client.php index 82570ca8f2a8..ef13551c96b2 100644 --- a/src/Logging/V2/LoggingServiceV2Client.php +++ b/src/Logging/V2/LoggingServiceV2Client.php @@ -30,805 +30,12 @@ namespace Google\Cloud\Logging\V2; -use Google\Api\MonitoredResource; -use Google\GAX\AgentHeaderDescriptor; -use Google\GAX\ApiCallable; -use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; -use Google\GAX\GrpcCredentialsHelper; -use Google\GAX\PageStreamingDescriptor; -use Google\GAX\PathTemplate; -use Google\Logging\V2\DeleteLogRequest; -use Google\Logging\V2\ListLogEntriesRequest; -use Google\Logging\V2\ListLogsRequest; -use Google\Logging\V2\ListMonitoredResourceDescriptorsRequest; -use Google\Logging\V2\LogEntry; -use Google\Logging\V2\LoggingServiceV2GrpcClient; -use Google\Logging\V2\WriteLogEntriesRequest; +use Google\Cloud\Logging\V2\Gapic\LoggingServiceV2GapicClient; /** - * Service Description: Service for ingesting and querying logs. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $loggingServiceV2Client = new LoggingServiceV2Client(); - * $formattedLogName = LoggingServiceV2Client::formatLogName("[PROJECT]", "[LOG]"); - * $loggingServiceV2Client->deleteLog($formattedLogName); - * } finally { - * $loggingServiceV2Client->close(); - * } - * ``` - * - * Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. - * - * @experimental + * {@inheritdoc} */ -class LoggingServiceV2Client +class LoggingServiceV2Client extends LoggingServiceV2GapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'logging.googleapis.com'; - - /** - * The default port of the service. - */ - const DEFAULT_SERVICE_PORT = 443; - - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - - /** - * The name of the code generator, to be included in the agent header. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $projectNameTemplate; - private static $logNameTemplate; - - private $grpcCredentialsHelper; - private $loggingServiceV2Stub; - private $scopes; - private $defaultCallSettings; - private $descriptors; - - /** - * Formats a string containing the fully-qualified path to represent - * a project resource. - * - * @param string $project - * - * @return string The formatted project resource. - * @experimental - */ - public static function formatProjectName($project) - { - return self::getProjectNameTemplate()->render([ - 'project' => $project, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a log resource. - * - * @param string $project - * @param string $log - * - * @return string The formatted log resource. - * @experimental - */ - public static function formatLogName($project, $log) - { - return self::getLogNameTemplate()->render([ - 'project' => $project, - 'log' => $log, - ]); - } - - /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - * - * @param string $projectName The fully-qualified project resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromProjectName($projectName) - { - return self::getProjectNameTemplate()->match($projectName)['project']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a log resource. - * - * @param string $logName The fully-qualified log resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromLogName($logName) - { - return self::getLogNameTemplate()->match($logName)['project']; - } - - /** - * Parses the log from the given fully-qualified path which - * represents a log resource. - * - * @param string $logName The fully-qualified log resource. - * - * @return string The extracted log value. - * @experimental - */ - public static function parseLogFromLogName($logName) - { - return self::getLogNameTemplate()->match($logName)['log']; - } - - private static function getProjectNameTemplate() - { - if (self::$projectNameTemplate == null) { - self::$projectNameTemplate = new PathTemplate('projects/{project}'); - } - - return self::$projectNameTemplate; - } - - private static function getLogNameTemplate() - { - if (self::$logNameTemplate == null) { - self::$logNameTemplate = new PathTemplate('projects/{project}/logs/{log}'); - } - - return self::$logNameTemplate; - } - - private static function getPageStreamingDescriptors() - { - $listLogEntriesPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getEntries', - ]); - $listMonitoredResourceDescriptorsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getResourceDescriptors', - ]); - $listLogsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getLogNames', - ]); - - $pageStreamingDescriptors = [ - 'listLogEntries' => $listLogEntriesPageStreamingDescriptor, - 'listMonitoredResourceDescriptors' => $listMonitoredResourceDescriptorsPageStreamingDescriptor, - 'listLogs' => $listLogsPageStreamingDescriptor, - ]; - - return $pageStreamingDescriptors; - } - - private static function getGapicVersion() - { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'logging.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Stackdriver Logging API. - * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'deleteLog' => $defaultDescriptors, - 'writeLogEntries' => $defaultDescriptors, - 'listLogEntries' => $defaultDescriptors, - 'listMonitoredResourceDescriptors' => $defaultDescriptors, - 'listLogs' => $defaultDescriptors, - ]; - $pageStreamingDescriptors = self::getPageStreamingDescriptors(); - foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { - $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/logging_service_v2_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.logging.v2.LoggingServiceV2', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createLoggingServiceV2StubFunction = function ($hostname, $opts) { - return new LoggingServiceV2GrpcClient($hostname, $opts); - }; - if (array_key_exists('createLoggingServiceV2StubFunction', $options)) { - $createLoggingServiceV2StubFunction = $options['createLoggingServiceV2StubFunction']; - } - $this->loggingServiceV2Stub = $this->grpcCredentialsHelper->createStub( - $createLoggingServiceV2StubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Deletes all the log entries in a log. - * The log reappears if it receives new entries. - * Log entries written shortly before the delete operation might not be - * deleted. - * - * Sample code: - * ``` - * try { - * $loggingServiceV2Client = new LoggingServiceV2Client(); - * $formattedLogName = LoggingServiceV2Client::formatLogName("[PROJECT]", "[LOG]"); - * $loggingServiceV2Client->deleteLog($formattedLogName); - * } finally { - * $loggingServiceV2Client->close(); - * } - * ``` - * - * @param string $logName Required. The resource name of the log to delete: - * - * "projects/[PROJECT_ID]/logs/[LOG_ID]" - * "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" - * "folders/[FOLDER_ID]/logs/[LOG_ID]" - * - * `[LOG_ID]` must be URL-encoded. For example, - * `"projects/my-project-id/logs/syslog"`, - * `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`. - * For more information about log names, see - * [LogEntry][google.logging.v2.LogEntry]. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function deleteLog($logName, $optionalArgs = []) - { - $request = new DeleteLogRequest(); - $request->setLogName($logName); - - $mergedSettings = $this->defaultCallSettings['deleteLog']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->loggingServiceV2Stub, - 'DeleteLog', - $mergedSettings, - $this->descriptors['deleteLog'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Writes log entries to Stackdriver Logging. - * - * Sample code: - * ``` - * try { - * $loggingServiceV2Client = new LoggingServiceV2Client(); - * $entries = []; - * $response = $loggingServiceV2Client->writeLogEntries($entries); - * } finally { - * $loggingServiceV2Client->close(); - * } - * ``` - * - * @param LogEntry[] $entries Required. The log entries to write. Values supplied for the fields - * `log_name`, `resource`, and `labels` in this `entries.write` request are - * inserted into those log entries in this list that do not provide their own - * values. - * - * Stackdriver Logging also creates and inserts values for `timestamp` and - * `insert_id` if the entries do not provide them. The created `insert_id` for - * the N'th entry in this list will be greater than earlier entries and less - * than later entries. Otherwise, the order of log entries in this list does - * not matter. - * - * To improve throughput and to avoid exceeding the - * [quota limit](https://cloud.google.com/logging/quota-policy) for calls to `entries.write`, - * you should write multiple log entries at once rather than - * calling this method for each individual log entry. - * @param array $optionalArgs { - * Optional. - * - * @type string $logName - * Optional. A default log resource name that is assigned to all log entries - * in `entries` that do not specify a value for `log_name`: - * - * "projects/[PROJECT_ID]/logs/[LOG_ID]" - * "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" - * "folders/[FOLDER_ID]/logs/[LOG_ID]" - * - * `[LOG_ID]` must be URL-encoded. For example, - * `"projects/my-project-id/logs/syslog"` or - * `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`. - * For more information about log names, see - * [LogEntry][google.logging.v2.LogEntry]. - * @type MonitoredResource $resource - * Optional. A default monitored resource object that is assigned to all log - * entries in `entries` that do not specify a value for `resource`. Example: - * - * { "type": "gce_instance", - * "labels": { - * "zone": "us-central1-a", "instance_id": "00000000000000000000" }} - * - * See [LogEntry][google.logging.v2.LogEntry]. - * @type array $labels - * Optional. Default labels that are added to the `labels` field of all log - * entries in `entries`. If a log entry already has a label with the same key - * as a label in this parameter, then the log entry's label is not changed. - * See [LogEntry][google.logging.v2.LogEntry]. - * @type bool $partialSuccess - * Optional. Whether valid entries should be written even if some other - * entries fail due to INVALID_ARGUMENT or PERMISSION_DENIED errors. If any - * entry is not written, then the response status is the error associated - * with one of the failed entries and the response includes error details - * keyed by the entries' zero-based index in the `entries.write` method. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Logging\V2\WriteLogEntriesResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function writeLogEntries($entries, $optionalArgs = []) - { - $request = new WriteLogEntriesRequest(); - $request->setEntries($entries); - if (isset($optionalArgs['logName'])) { - $request->setLogName($optionalArgs['logName']); - } - if (isset($optionalArgs['resource'])) { - $request->setResource($optionalArgs['resource']); - } - if (isset($optionalArgs['labels'])) { - $request->setLabels($optionalArgs['labels']); - } - if (isset($optionalArgs['partialSuccess'])) { - $request->setPartialSuccess($optionalArgs['partialSuccess']); - } - - $mergedSettings = $this->defaultCallSettings['writeLogEntries']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->loggingServiceV2Stub, - 'WriteLogEntries', - $mergedSettings, - $this->descriptors['writeLogEntries'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists log entries. Use this method to retrieve log entries from - * Stackdriver Logging. For ways to export log entries, see - * [Exporting Logs](https://cloud.google.com/logging/docs/export). - * - * Sample code: - * ``` - * try { - * $loggingServiceV2Client = new LoggingServiceV2Client(); - * $resourceNames = []; - * // Iterate through all elements - * $pagedResponse = $loggingServiceV2Client->listLogEntries($resourceNames); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $loggingServiceV2Client->listLogEntries($resourceNames, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $loggingServiceV2Client->close(); - * } - * ``` - * - * @param string[] $resourceNames Required. Names of one or more parent resources from which to - * retrieve log entries: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * - * Projects listed in the `project_ids` field are added to this list. - * @param array $optionalArgs { - * Optional. - * - * @type string[] $projectIds - * Deprecated. Use `resource_names` instead. One or more project identifiers - * or project numbers from which to retrieve log entries. Example: - * `"my-project-1A"`. If present, these project identifiers are converted to - * resource name format and added to the list of resources in - * `resource_names`. - * @type string $filter - * Optional. A filter that chooses which log entries to return. See [Advanced - * Logs Filters](https://cloud.google.com/logging/docs/view/advanced_filters). Only log entries that - * match the filter are returned. An empty filter matches all log entries in - * the resources listed in `resource_names`. Referencing a parent resource - * that is not listed in `resource_names` will cause the filter to return no - * results. - * The maximum length of the filter is 20000 characters. - * @type string $orderBy - * Optional. How the results should be sorted. Presently, the only permitted - * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first - * option returns entries in order of increasing values of - * `LogEntry.timestamp` (oldest first), and the second option returns entries - * in order of decreasing timestamps (newest first). Entries with equal - * timestamps are returned in order of their `insert_id` values. - * @type int $pageSize - * The maximum number of resources contained in the underlying API - * response. The API may return fewer values in a page, even if - * there are additional values to be retrieved. - * @type string $pageToken - * A page token is used to specify a page of values to be returned. - * If no page token is specified (the default), the first page - * of values will be returned. Any page token used here must have - * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listLogEntries($resourceNames, $optionalArgs = []) - { - $request = new ListLogEntriesRequest(); - $request->setResourceNames($resourceNames); - if (isset($optionalArgs['projectIds'])) { - $request->setProjectIds($optionalArgs['projectIds']); - } - if (isset($optionalArgs['filter'])) { - $request->setFilter($optionalArgs['filter']); - } - if (isset($optionalArgs['orderBy'])) { - $request->setOrderBy($optionalArgs['orderBy']); - } - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listLogEntries']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->loggingServiceV2Stub, - 'ListLogEntries', - $mergedSettings, - $this->descriptors['listLogEntries'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists the descriptors for monitored resource types used by Stackdriver - * Logging. - * - * Sample code: - * ``` - * try { - * $loggingServiceV2Client = new LoggingServiceV2Client(); - * - * // Iterate through all elements - * $pagedResponse = $loggingServiceV2Client->listMonitoredResourceDescriptors(); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $loggingServiceV2Client->listMonitoredResourceDescriptors(['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $loggingServiceV2Client->close(); - * } - * ``` - * - * @param array $optionalArgs { - * Optional. - * - * @type int $pageSize - * The maximum number of resources contained in the underlying API - * response. The API may return fewer values in a page, even if - * there are additional values to be retrieved. - * @type string $pageToken - * A page token is used to specify a page of values to be returned. - * If no page token is specified (the default), the first page - * of values will be returned. Any page token used here must have - * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listMonitoredResourceDescriptors($optionalArgs = []) - { - $request = new ListMonitoredResourceDescriptorsRequest(); - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listMonitoredResourceDescriptors']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->loggingServiceV2Stub, - 'ListMonitoredResourceDescriptors', - $mergedSettings, - $this->descriptors['listMonitoredResourceDescriptors'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists the logs in projects, organizations, folders, or billing accounts. - * Only logs that have entries are listed. - * - * Sample code: - * ``` - * try { - * $loggingServiceV2Client = new LoggingServiceV2Client(); - * $formattedParent = LoggingServiceV2Client::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $loggingServiceV2Client->listLogs($formattedParent); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $loggingServiceV2Client->listLogs($formattedParent, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $loggingServiceV2Client->close(); - * } - * ``` - * - * @param string $parent Required. The resource name that owns the logs: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * @param array $optionalArgs { - * Optional. - * - * @type int $pageSize - * The maximum number of resources contained in the underlying API - * response. The API may return fewer values in a page, even if - * there are additional values to be retrieved. - * @type string $pageToken - * A page token is used to specify a page of values to be returned. - * If no page token is specified (the default), the first page - * of values will be returned. Any page token used here must have - * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listLogs($parent, $optionalArgs = []) - { - $request = new ListLogsRequest(); - $request->setParent($parent); - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listLogs']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->loggingServiceV2Stub, - 'ListLogs', - $mergedSettings, - $this->descriptors['listLogs'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->loggingServiceV2Stub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see LoggingServiceV2ClientImpl} class. } diff --git a/src/Logging/V2/MetricsServiceV2Client.php b/src/Logging/V2/MetricsServiceV2Client.php index 82586089bfee..8634ed20493a 100644 --- a/src/Logging/V2/MetricsServiceV2Client.php +++ b/src/Logging/V2/MetricsServiceV2Client.php @@ -30,646 +30,12 @@ namespace Google\Cloud\Logging\V2; -use Google\GAX\AgentHeaderDescriptor; -use Google\GAX\ApiCallable; -use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; -use Google\GAX\GrpcCredentialsHelper; -use Google\GAX\PageStreamingDescriptor; -use Google\GAX\PathTemplate; -use Google\Logging\V2\CreateLogMetricRequest; -use Google\Logging\V2\DeleteLogMetricRequest; -use Google\Logging\V2\GetLogMetricRequest; -use Google\Logging\V2\ListLogMetricsRequest; -use Google\Logging\V2\LogMetric; -use Google\Logging\V2\MetricsServiceV2GrpcClient; -use Google\Logging\V2\UpdateLogMetricRequest; +use Google\Cloud\Logging\V2\Gapic\MetricsServiceV2GapicClient; /** - * Service Description: Service for configuring logs-based metrics. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $metricsServiceV2Client = new MetricsServiceV2Client(); - * $formattedParent = MetricsServiceV2Client::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $metricsServiceV2Client->listLogMetrics($formattedParent); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $metricsServiceV2Client->listLogMetrics($formattedParent, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $metricsServiceV2Client->close(); - * } - * ``` - * - * Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. - * - * @experimental + * {@inheritdoc} */ -class MetricsServiceV2Client +class MetricsServiceV2Client extends MetricsServiceV2GapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'logging.googleapis.com'; - - /** - * The default port of the service. - */ - const DEFAULT_SERVICE_PORT = 443; - - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - - /** - * The name of the code generator, to be included in the agent header. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $projectNameTemplate; - private static $metricNameTemplate; - - private $grpcCredentialsHelper; - private $metricsServiceV2Stub; - private $scopes; - private $defaultCallSettings; - private $descriptors; - - /** - * Formats a string containing the fully-qualified path to represent - * a project resource. - * - * @param string $project - * - * @return string The formatted project resource. - * @experimental - */ - public static function formatProjectName($project) - { - return self::getProjectNameTemplate()->render([ - 'project' => $project, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a metric resource. - * - * @param string $project - * @param string $metric - * - * @return string The formatted metric resource. - * @experimental - */ - public static function formatMetricName($project, $metric) - { - return self::getMetricNameTemplate()->render([ - 'project' => $project, - 'metric' => $metric, - ]); - } - - /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - * - * @param string $projectName The fully-qualified project resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromProjectName($projectName) - { - return self::getProjectNameTemplate()->match($projectName)['project']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a metric resource. - * - * @param string $metricName The fully-qualified metric resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromMetricName($metricName) - { - return self::getMetricNameTemplate()->match($metricName)['project']; - } - - /** - * Parses the metric from the given fully-qualified path which - * represents a metric resource. - * - * @param string $metricName The fully-qualified metric resource. - * - * @return string The extracted metric value. - * @experimental - */ - public static function parseMetricFromMetricName($metricName) - { - return self::getMetricNameTemplate()->match($metricName)['metric']; - } - - private static function getProjectNameTemplate() - { - if (self::$projectNameTemplate == null) { - self::$projectNameTemplate = new PathTemplate('projects/{project}'); - } - - return self::$projectNameTemplate; - } - - private static function getMetricNameTemplate() - { - if (self::$metricNameTemplate == null) { - self::$metricNameTemplate = new PathTemplate('projects/{project}/metrics/{metric}'); - } - - return self::$metricNameTemplate; - } - - private static function getPageStreamingDescriptors() - { - $listLogMetricsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getMetrics', - ]); - - $pageStreamingDescriptors = [ - 'listLogMetrics' => $listLogMetricsPageStreamingDescriptor, - ]; - - return $pageStreamingDescriptors; - } - - private static function getGapicVersion() - { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'logging.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Stackdriver Logging API. - * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'listLogMetrics' => $defaultDescriptors, - 'getLogMetric' => $defaultDescriptors, - 'createLogMetric' => $defaultDescriptors, - 'updateLogMetric' => $defaultDescriptors, - 'deleteLogMetric' => $defaultDescriptors, - ]; - $pageStreamingDescriptors = self::getPageStreamingDescriptors(); - foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { - $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/metrics_service_v2_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.logging.v2.MetricsServiceV2', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createMetricsServiceV2StubFunction = function ($hostname, $opts) { - return new MetricsServiceV2GrpcClient($hostname, $opts); - }; - if (array_key_exists('createMetricsServiceV2StubFunction', $options)) { - $createMetricsServiceV2StubFunction = $options['createMetricsServiceV2StubFunction']; - } - $this->metricsServiceV2Stub = $this->grpcCredentialsHelper->createStub( - $createMetricsServiceV2StubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Lists logs-based metrics. - * - * Sample code: - * ``` - * try { - * $metricsServiceV2Client = new MetricsServiceV2Client(); - * $formattedParent = MetricsServiceV2Client::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $metricsServiceV2Client->listLogMetrics($formattedParent); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $metricsServiceV2Client->listLogMetrics($formattedParent, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $metricsServiceV2Client->close(); - * } - * ``` - * - * @param string $parent Required. The name of the project containing the metrics: - * - * "projects/[PROJECT_ID]" - * @param array $optionalArgs { - * Optional. - * - * @type string $pageToken - * A page token is used to specify a page of values to be returned. - * If no page token is specified (the default), the first page - * of values will be returned. Any page token used here must have - * been generated by a previous call to the API. - * @type int $pageSize - * The maximum number of resources contained in the underlying API - * response. The API may return fewer values in a page, even if - * there are additional values to be retrieved. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listLogMetrics($parent, $optionalArgs = []) - { - $request = new ListLogMetricsRequest(); - $request->setParent($parent); - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - - $mergedSettings = $this->defaultCallSettings['listLogMetrics']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricsServiceV2Stub, - 'ListLogMetrics', - $mergedSettings, - $this->descriptors['listLogMetrics'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets a logs-based metric. - * - * Sample code: - * ``` - * try { - * $metricsServiceV2Client = new MetricsServiceV2Client(); - * $formattedMetricName = MetricsServiceV2Client::formatMetricName("[PROJECT]", "[METRIC]"); - * $response = $metricsServiceV2Client->getLogMetric($formattedMetricName); - * } finally { - * $metricsServiceV2Client->close(); - * } - * ``` - * - * @param string $metricName The resource name of the desired metric: - * - * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Logging\V2\LogMetric - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getLogMetric($metricName, $optionalArgs = []) - { - $request = new GetLogMetricRequest(); - $request->setMetricName($metricName); - - $mergedSettings = $this->defaultCallSettings['getLogMetric']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricsServiceV2Stub, - 'GetLogMetric', - $mergedSettings, - $this->descriptors['getLogMetric'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Creates a logs-based metric. - * - * Sample code: - * ``` - * try { - * $metricsServiceV2Client = new MetricsServiceV2Client(); - * $formattedParent = MetricsServiceV2Client::formatProjectName("[PROJECT]"); - * $metric = new LogMetric(); - * $response = $metricsServiceV2Client->createLogMetric($formattedParent, $metric); - * } finally { - * $metricsServiceV2Client->close(); - * } - * ``` - * - * @param string $parent The resource name of the project in which to create the metric: - * - * "projects/[PROJECT_ID]" - * - * The new metric must be provided in the request. - * @param LogMetric $metric The new logs-based metric, which must not have an identifier that - * already exists. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Logging\V2\LogMetric - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createLogMetric($parent, $metric, $optionalArgs = []) - { - $request = new CreateLogMetricRequest(); - $request->setParent($parent); - $request->setMetric($metric); - - $mergedSettings = $this->defaultCallSettings['createLogMetric']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricsServiceV2Stub, - 'CreateLogMetric', - $mergedSettings, - $this->descriptors['createLogMetric'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Creates or updates a logs-based metric. - * - * Sample code: - * ``` - * try { - * $metricsServiceV2Client = new MetricsServiceV2Client(); - * $formattedMetricName = MetricsServiceV2Client::formatMetricName("[PROJECT]", "[METRIC]"); - * $metric = new LogMetric(); - * $response = $metricsServiceV2Client->updateLogMetric($formattedMetricName, $metric); - * } finally { - * $metricsServiceV2Client->close(); - * } - * ``` - * - * @param string $metricName The resource name of the metric to update: - * - * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - * - * The updated metric must be provided in the request and it's - * `name` field must be the same as `[METRIC_ID]` If the metric - * does not exist in `[PROJECT_ID]`, then a new metric is created. - * @param LogMetric $metric The updated metric. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Logging\V2\LogMetric - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function updateLogMetric($metricName, $metric, $optionalArgs = []) - { - $request = new UpdateLogMetricRequest(); - $request->setMetricName($metricName); - $request->setMetric($metric); - - $mergedSettings = $this->defaultCallSettings['updateLogMetric']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricsServiceV2Stub, - 'UpdateLogMetric', - $mergedSettings, - $this->descriptors['updateLogMetric'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Deletes a logs-based metric. - * - * Sample code: - * ``` - * try { - * $metricsServiceV2Client = new MetricsServiceV2Client(); - * $formattedMetricName = MetricsServiceV2Client::formatMetricName("[PROJECT]", "[METRIC]"); - * $metricsServiceV2Client->deleteLogMetric($formattedMetricName); - * } finally { - * $metricsServiceV2Client->close(); - * } - * ``` - * - * @param string $metricName The resource name of the metric to delete: - * - * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function deleteLogMetric($metricName, $optionalArgs = []) - { - $request = new DeleteLogMetricRequest(); - $request->setMetricName($metricName); - - $mergedSettings = $this->defaultCallSettings['deleteLogMetric']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricsServiceV2Stub, - 'DeleteLogMetric', - $mergedSettings, - $this->descriptors['deleteLogMetric'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->metricsServiceV2Stub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see MetricsServiceV2ClientImpl} class. } diff --git a/src/Monitoring/V3/Gapic/GroupServiceGapicClient.php b/src/Monitoring/V3/Gapic/GroupServiceGapicClient.php new file mode 100644 index 000000000000..05475a813410 --- /dev/null +++ b/src/Monitoring/V3/Gapic/GroupServiceGapicClient.php @@ -0,0 +1,817 @@ +listGroups($formattedName); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $groupServiceClient->listGroups($formattedName, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $groupServiceClient->close(); + * } + * ``` + * + * Many parameters require resource names to be formatted in a particular way. To assist + * with these names, this class includes a format method for each type of name, and additionally + * a parse method to extract the individual identifiers contained within names that are + * returned. + * + * @experimental + */ +class GroupServiceGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'monitoring.googleapis.com'; + + /** + * The default port of the service. + */ + const DEFAULT_SERVICE_PORT = 443; + + /** + * The default timeout for non-retrying methods. + */ + const DEFAULT_TIMEOUT_MILLIS = 30000; + + /** + * The name of the code generator, to be included in the agent header. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $projectNameTemplate; + private static $groupNameTemplate; + + protected $grpcCredentialsHelper; + protected $groupServiceStub; + private $scopes; + private $defaultCallSettings; + private $descriptors; + + /** + * Formats a string containing the fully-qualified path to represent + * a project resource. + * + * @param string $project + * + * @return string The formatted project resource. + * @experimental + */ + public static function formatProjectName($project) + { + return self::getProjectNameTemplate()->render([ + 'project' => $project, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a group resource. + * + * @param string $project + * @param string $group + * + * @return string The formatted group resource. + * @experimental + */ + public static function formatGroupName($project, $group) + { + return self::getGroupNameTemplate()->render([ + 'project' => $project, + 'group' => $group, + ]); + } + + /** + * Parses the project from the given fully-qualified path which + * represents a project resource. + * + * @param string $projectName The fully-qualified project resource. + * + * @return string The extracted project value. + * @experimental + */ + public static function parseProjectFromProjectName($projectName) + { + return self::getProjectNameTemplate()->match($projectName)['project']; + } + + /** + * Parses the project from the given fully-qualified path which + * represents a group resource. + * + * @param string $groupName The fully-qualified group resource. + * + * @return string The extracted project value. + * @experimental + */ + public static function parseProjectFromGroupName($groupName) + { + return self::getGroupNameTemplate()->match($groupName)['project']; + } + + /** + * Parses the group from the given fully-qualified path which + * represents a group resource. + * + * @param string $groupName The fully-qualified group resource. + * + * @return string The extracted group value. + * @experimental + */ + public static function parseGroupFromGroupName($groupName) + { + return self::getGroupNameTemplate()->match($groupName)['group']; + } + + private static function getProjectNameTemplate() + { + if (self::$projectNameTemplate == null) { + self::$projectNameTemplate = new PathTemplate('projects/{project}'); + } + + return self::$projectNameTemplate; + } + + private static function getGroupNameTemplate() + { + if (self::$groupNameTemplate == null) { + self::$groupNameTemplate = new PathTemplate('projects/{project}/groups/{group}'); + } + + return self::$groupNameTemplate; + } + + private static function getPageStreamingDescriptors() + { + $listGroupsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getGroup', + ]); + $listGroupMembersPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getMembers', + ]); + + $pageStreamingDescriptors = [ + 'listGroups' => $listGroupsPageStreamingDescriptor, + 'listGroupMembers' => $listGroupMembersPageStreamingDescriptor, + ]; + + return $pageStreamingDescriptors; + } + + private static function getGapicVersion() + { + if (file_exists(__DIR__.'/../VERSION')) { + return trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { + return \Google\Cloud\ServiceBuilder::VERSION; + } else { + return; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'monitoring.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * A CredentialsLoader object created using the Google\Auth library. + * @type array $scopes A string array of scopes to use when acquiring credentials. + * Defaults to the scopes for the Stackdriver Monitoring API. + * @type array $retryingOverride + * An associative array of string => RetryOptions, where the keys + * are method names (e.g. 'createFoo'), that overrides default retrying + * settings. A value of null indicates that the method in question should + * not retry. + * @type int $timeoutMillis The timeout in milliseconds to use for calls + * that don't use retries. For calls that use retries, + * set the timeout in RetryOptions. + * Default: 30000 (30 seconds) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/monitoring', + 'https://www.googleapis.com/auth/monitoring.read', + 'https://www.googleapis.com/auth/monitoring.write', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'listGroups' => $defaultDescriptors, + 'getGroup' => $defaultDescriptors, + 'createGroup' => $defaultDescriptors, + 'updateGroup' => $defaultDescriptors, + 'deleteGroup' => $defaultDescriptors, + 'listGroupMembers' => $defaultDescriptors, + ]; + $pageStreamingDescriptors = self::getPageStreamingDescriptors(); + foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { + $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/group_service_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.monitoring.v3.GroupService', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createGroupServiceStubFunction = function ($hostname, $opts, $channel) { + return new GroupServiceGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createGroupServiceStubFunction', $options)) { + $createGroupServiceStubFunction = $options['createGroupServiceStubFunction']; + } + $this->groupServiceStub = $this->grpcCredentialsHelper->createStub($createGroupServiceStubFunction); + } + + /** + * Lists the existing groups. + * + * Sample code: + * ``` + * try { + * $groupServiceClient = new GroupServiceClient(); + * $formattedName = GroupServiceClient::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $groupServiceClient->listGroups($formattedName); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $groupServiceClient->listGroups($formattedName, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $groupServiceClient->close(); + * } + * ``` + * + * @param string $name The project whose groups are to be listed. The format is + * `"projects/{project_id_or_number}"`. + * @param array $optionalArgs { + * Optional. + * + * @type string $childrenOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns groups whose `parentName` field contains the group + * name. If no groups have this parent, the results are empty. + * @type string $ancestorsOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns groups that are ancestors of the specified group. + * The groups are returned in order, starting with the immediate parent and + * ending with the most distant ancestor. If the specified group has no + * immediate parent, the results are empty. + * @type string $descendantsOfGroup + * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. + * Returns the descendants of the specified group. This is a superset of + * the results returned by the `childrenOfGroup` filter, and includes + * children-of-children, and so forth. + * @type int $pageSize + * The maximum number of resources contained in the underlying API + * response. The API may return fewer values in a page, even if + * there are additional values to be retrieved. + * @type string $pageToken + * A page token is used to specify a page of values to be returned. + * If no page token is specified (the default), the first page + * of values will be returned. Any page token used here must have + * been generated by a previous call to the API. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listGroups($name, $optionalArgs = []) + { + $request = new ListGroupsRequest(); + $request->setName($name); + if (isset($optionalArgs['childrenOfGroup'])) { + $request->setChildrenOfGroup($optionalArgs['childrenOfGroup']); + } + if (isset($optionalArgs['ancestorsOfGroup'])) { + $request->setAncestorsOfGroup($optionalArgs['ancestorsOfGroup']); + } + if (isset($optionalArgs['descendantsOfGroup'])) { + $request->setDescendantsOfGroup($optionalArgs['descendantsOfGroup']); + } + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listGroups']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->groupServiceStub, + 'ListGroups', + $mergedSettings, + $this->descriptors['listGroups'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets a single group. + * + * Sample code: + * ``` + * try { + * $groupServiceClient = new GroupServiceClient(); + * $formattedName = GroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); + * $response = $groupServiceClient->getGroup($formattedName); + * } finally { + * $groupServiceClient->close(); + * } + * ``` + * + * @param string $name The group to retrieve. The format is + * `"projects/{project_id_or_number}/groups/{group_id}"`. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Monitoring\V3\Group + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getGroup($name, $optionalArgs = []) + { + $request = new GetGroupRequest(); + $request->setName($name); + + $mergedSettings = $this->defaultCallSettings['getGroup']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->groupServiceStub, + 'GetGroup', + $mergedSettings, + $this->descriptors['getGroup'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Creates a new group. + * + * Sample code: + * ``` + * try { + * $groupServiceClient = new GroupServiceClient(); + * $formattedName = GroupServiceClient::formatProjectName("[PROJECT]"); + * $group = new Group(); + * $response = $groupServiceClient->createGroup($formattedName, $group); + * } finally { + * $groupServiceClient->close(); + * } + * ``` + * + * @param string $name The project in which to create the group. The format is + * `"projects/{project_id_or_number}"`. + * @param Group $group A group definition. It is an error to define the `name` field because + * the system assigns the name. + * @param array $optionalArgs { + * Optional. + * + * @type bool $validateOnly + * If true, validate this request but do not create the group. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Monitoring\V3\Group + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createGroup($name, $group, $optionalArgs = []) + { + $request = new CreateGroupRequest(); + $request->setName($name); + $request->setGroup($group); + if (isset($optionalArgs['validateOnly'])) { + $request->setValidateOnly($optionalArgs['validateOnly']); + } + + $mergedSettings = $this->defaultCallSettings['createGroup']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->groupServiceStub, + 'CreateGroup', + $mergedSettings, + $this->descriptors['createGroup'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Updates an existing group. + * You can change any group attributes except `name`. + * + * Sample code: + * ``` + * try { + * $groupServiceClient = new GroupServiceClient(); + * $group = new Group(); + * $response = $groupServiceClient->updateGroup($group); + * } finally { + * $groupServiceClient->close(); + * } + * ``` + * + * @param Group $group The new definition of the group. All fields of the existing group, + * excepting `name`, are replaced with the corresponding fields of this group. + * @param array $optionalArgs { + * Optional. + * + * @type bool $validateOnly + * If true, validate this request but do not update the existing group. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Monitoring\V3\Group + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function updateGroup($group, $optionalArgs = []) + { + $request = new UpdateGroupRequest(); + $request->setGroup($group); + if (isset($optionalArgs['validateOnly'])) { + $request->setValidateOnly($optionalArgs['validateOnly']); + } + + $mergedSettings = $this->defaultCallSettings['updateGroup']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->groupServiceStub, + 'UpdateGroup', + $mergedSettings, + $this->descriptors['updateGroup'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Deletes an existing group. + * + * Sample code: + * ``` + * try { + * $groupServiceClient = new GroupServiceClient(); + * $formattedName = GroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); + * $groupServiceClient->deleteGroup($formattedName); + * } finally { + * $groupServiceClient->close(); + * } + * ``` + * + * @param string $name The group to delete. The format is + * `"projects/{project_id_or_number}/groups/{group_id}"`. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function deleteGroup($name, $optionalArgs = []) + { + $request = new DeleteGroupRequest(); + $request->setName($name); + + $mergedSettings = $this->defaultCallSettings['deleteGroup']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->groupServiceStub, + 'DeleteGroup', + $mergedSettings, + $this->descriptors['deleteGroup'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists the monitored resources that are members of a group. + * + * Sample code: + * ``` + * try { + * $groupServiceClient = new GroupServiceClient(); + * $formattedName = GroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); + * // Iterate through all elements + * $pagedResponse = $groupServiceClient->listGroupMembers($formattedName); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $groupServiceClient->listGroupMembers($formattedName, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $groupServiceClient->close(); + * } + * ``` + * + * @param string $name The group whose members are listed. The format is + * `"projects/{project_id_or_number}/groups/{group_id}"`. + * @param array $optionalArgs { + * Optional. + * + * @type int $pageSize + * The maximum number of resources contained in the underlying API + * response. The API may return fewer values in a page, even if + * there are additional values to be retrieved. + * @type string $pageToken + * A page token is used to specify a page of values to be returned. + * If no page token is specified (the default), the first page + * of values will be returned. Any page token used here must have + * been generated by a previous call to the API. + * @type string $filter + * An optional [list filter](https://cloud.google.com/monitoring/api/learn_more#filtering) describing + * the members to be returned. The filter may reference the type, labels, and + * metadata of monitored resources that comprise the group. + * For example, to return only resources representing Compute Engine VM + * instances, use this filter: + * + * resource.type = "gce_instance" + * @type TimeInterval $interval + * An optional time interval for which results should be returned. Only + * members that were part of the group during the specified interval are + * included in the response. If no interval is provided then the group + * membership over the last minute is returned. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listGroupMembers($name, $optionalArgs = []) + { + $request = new ListGroupMembersRequest(); + $request->setName($name); + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + if (isset($optionalArgs['filter'])) { + $request->setFilter($optionalArgs['filter']); + } + if (isset($optionalArgs['interval'])) { + $request->setInterval($optionalArgs['interval']); + } + + $mergedSettings = $this->defaultCallSettings['listGroupMembers']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->groupServiceStub, + 'ListGroupMembers', + $mergedSettings, + $this->descriptors['listGroupMembers'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->groupServiceStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/Monitoring/V3/Gapic/MetricServiceGapicClient.php b/src/Monitoring/V3/Gapic/MetricServiceGapicClient.php new file mode 100644 index 000000000000..b50d330297fa --- /dev/null +++ b/src/Monitoring/V3/Gapic/MetricServiceGapicClient.php @@ -0,0 +1,1031 @@ +listMonitoredResourceDescriptors($formattedName); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $metricServiceClient->listMonitoredResourceDescriptors($formattedName, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $metricServiceClient->close(); + * } + * ``` + * + * Many parameters require resource names to be formatted in a particular way. To assist + * with these names, this class includes a format method for each type of name, and additionally + * a parse method to extract the individual identifiers contained within names that are + * returned. + * + * @experimental + */ +class MetricServiceGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'monitoring.googleapis.com'; + + /** + * The default port of the service. + */ + const DEFAULT_SERVICE_PORT = 443; + + /** + * The default timeout for non-retrying methods. + */ + const DEFAULT_TIMEOUT_MILLIS = 30000; + + /** + * The name of the code generator, to be included in the agent header. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $projectNameTemplate; + private static $metricDescriptorNameTemplate; + private static $monitoredResourceDescriptorNameTemplate; + + protected $grpcCredentialsHelper; + protected $metricServiceStub; + private $scopes; + private $defaultCallSettings; + private $descriptors; + + /** + * Formats a string containing the fully-qualified path to represent + * a project resource. + * + * @param string $project + * + * @return string The formatted project resource. + * @experimental + */ + public static function formatProjectName($project) + { + return self::getProjectNameTemplate()->render([ + 'project' => $project, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a metric_descriptor resource. + * + * @param string $project + * @param string $metricDescriptor + * + * @return string The formatted metric_descriptor resource. + * @experimental + */ + public static function formatMetricDescriptorName($project, $metricDescriptor) + { + return self::getMetricDescriptorNameTemplate()->render([ + 'project' => $project, + 'metric_descriptor' => $metricDescriptor, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a monitored_resource_descriptor resource. + * + * @param string $project + * @param string $monitoredResourceDescriptor + * + * @return string The formatted monitored_resource_descriptor resource. + * @experimental + */ + public static function formatMonitoredResourceDescriptorName($project, $monitoredResourceDescriptor) + { + return self::getMonitoredResourceDescriptorNameTemplate()->render([ + 'project' => $project, + 'monitored_resource_descriptor' => $monitoredResourceDescriptor, + ]); + } + + /** + * Parses the project from the given fully-qualified path which + * represents a project resource. + * + * @param string $projectName The fully-qualified project resource. + * + * @return string The extracted project value. + * @experimental + */ + public static function parseProjectFromProjectName($projectName) + { + return self::getProjectNameTemplate()->match($projectName)['project']; + } + + /** + * Parses the project from the given fully-qualified path which + * represents a metric_descriptor resource. + * + * @param string $metricDescriptorName The fully-qualified metric_descriptor resource. + * + * @return string The extracted project value. + * @experimental + */ + public static function parseProjectFromMetricDescriptorName($metricDescriptorName) + { + return self::getMetricDescriptorNameTemplate()->match($metricDescriptorName)['project']; + } + + /** + * Parses the metric_descriptor from the given fully-qualified path which + * represents a metric_descriptor resource. + * + * @param string $metricDescriptorName The fully-qualified metric_descriptor resource. + * + * @return string The extracted metric_descriptor value. + * @experimental + */ + public static function parseMetricDescriptorFromMetricDescriptorName($metricDescriptorName) + { + return self::getMetricDescriptorNameTemplate()->match($metricDescriptorName)['metric_descriptor']; + } + + /** + * Parses the project from the given fully-qualified path which + * represents a monitored_resource_descriptor resource. + * + * @param string $monitoredResourceDescriptorName The fully-qualified monitored_resource_descriptor resource. + * + * @return string The extracted project value. + * @experimental + */ + public static function parseProjectFromMonitoredResourceDescriptorName($monitoredResourceDescriptorName) + { + return self::getMonitoredResourceDescriptorNameTemplate()->match($monitoredResourceDescriptorName)['project']; + } + + /** + * Parses the monitored_resource_descriptor from the given fully-qualified path which + * represents a monitored_resource_descriptor resource. + * + * @param string $monitoredResourceDescriptorName The fully-qualified monitored_resource_descriptor resource. + * + * @return string The extracted monitored_resource_descriptor value. + * @experimental + */ + public static function parseMonitoredResourceDescriptorFromMonitoredResourceDescriptorName($monitoredResourceDescriptorName) + { + return self::getMonitoredResourceDescriptorNameTemplate()->match($monitoredResourceDescriptorName)['monitored_resource_descriptor']; + } + + private static function getProjectNameTemplate() + { + if (self::$projectNameTemplate == null) { + self::$projectNameTemplate = new PathTemplate('projects/{project}'); + } + + return self::$projectNameTemplate; + } + + private static function getMetricDescriptorNameTemplate() + { + if (self::$metricDescriptorNameTemplate == null) { + self::$metricDescriptorNameTemplate = new PathTemplate('projects/{project}/metricDescriptors/{metric_descriptor=**}'); + } + + return self::$metricDescriptorNameTemplate; + } + + private static function getMonitoredResourceDescriptorNameTemplate() + { + if (self::$monitoredResourceDescriptorNameTemplate == null) { + self::$monitoredResourceDescriptorNameTemplate = new PathTemplate('projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}'); + } + + return self::$monitoredResourceDescriptorNameTemplate; + } + + private static function getPageStreamingDescriptors() + { + $listMonitoredResourceDescriptorsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getResourceDescriptors', + ]); + $listMetricDescriptorsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getMetricDescriptors', + ]); + $listTimeSeriesPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getTimeSeries', + ]); + + $pageStreamingDescriptors = [ + 'listMonitoredResourceDescriptors' => $listMonitoredResourceDescriptorsPageStreamingDescriptor, + 'listMetricDescriptors' => $listMetricDescriptorsPageStreamingDescriptor, + 'listTimeSeries' => $listTimeSeriesPageStreamingDescriptor, + ]; + + return $pageStreamingDescriptors; + } + + private static function getGapicVersion() + { + if (file_exists(__DIR__.'/../VERSION')) { + return trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { + return \Google\Cloud\ServiceBuilder::VERSION; + } else { + return; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'monitoring.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * A CredentialsLoader object created using the Google\Auth library. + * @type array $scopes A string array of scopes to use when acquiring credentials. + * Defaults to the scopes for the Stackdriver Monitoring API. + * @type array $retryingOverride + * An associative array of string => RetryOptions, where the keys + * are method names (e.g. 'createFoo'), that overrides default retrying + * settings. A value of null indicates that the method in question should + * not retry. + * @type int $timeoutMillis The timeout in milliseconds to use for calls + * that don't use retries. For calls that use retries, + * set the timeout in RetryOptions. + * Default: 30000 (30 seconds) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/monitoring', + 'https://www.googleapis.com/auth/monitoring.read', + 'https://www.googleapis.com/auth/monitoring.write', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'listMonitoredResourceDescriptors' => $defaultDescriptors, + 'getMonitoredResourceDescriptor' => $defaultDescriptors, + 'listMetricDescriptors' => $defaultDescriptors, + 'getMetricDescriptor' => $defaultDescriptors, + 'createMetricDescriptor' => $defaultDescriptors, + 'deleteMetricDescriptor' => $defaultDescriptors, + 'listTimeSeries' => $defaultDescriptors, + 'createTimeSeries' => $defaultDescriptors, + ]; + $pageStreamingDescriptors = self::getPageStreamingDescriptors(); + foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { + $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/metric_service_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.monitoring.v3.MetricService', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createMetricServiceStubFunction = function ($hostname, $opts, $channel) { + return new MetricServiceGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createMetricServiceStubFunction', $options)) { + $createMetricServiceStubFunction = $options['createMetricServiceStubFunction']; + } + $this->metricServiceStub = $this->grpcCredentialsHelper->createStub($createMetricServiceStubFunction); + } + + /** + * Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. + * + * Sample code: + * ``` + * try { + * $metricServiceClient = new MetricServiceClient(); + * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $metricServiceClient->listMonitoredResourceDescriptors($formattedName); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $metricServiceClient->listMonitoredResourceDescriptors($formattedName, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $metricServiceClient->close(); + * } + * ``` + * + * @param string $name The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param array $optionalArgs { + * Optional. + * + * @type string $filter + * An optional [filter](https://cloud.google.com/monitoring/api/v3/filters) describing + * the descriptors to be returned. The filter can reference + * the descriptor's type and labels. For example, the + * following filter returns only Google Compute Engine descriptors + * that have an `id` label: + * + * resource.type = starts_with("gce_") AND resource.label:id + * @type int $pageSize + * The maximum number of resources contained in the underlying API + * response. The API may return fewer values in a page, even if + * there are additional values to be retrieved. + * @type string $pageToken + * A page token is used to specify a page of values to be returned. + * If no page token is specified (the default), the first page + * of values will be returned. Any page token used here must have + * been generated by a previous call to the API. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listMonitoredResourceDescriptors($name, $optionalArgs = []) + { + $request = new ListMonitoredResourceDescriptorsRequest(); + $request->setName($name); + if (isset($optionalArgs['filter'])) { + $request->setFilter($optionalArgs['filter']); + } + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listMonitoredResourceDescriptors']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricServiceStub, + 'ListMonitoredResourceDescriptors', + $mergedSettings, + $this->descriptors['listMonitoredResourceDescriptors'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets a single monitored resource descriptor. This method does not require a Stackdriver account. + * + * Sample code: + * ``` + * try { + * $metricServiceClient = new MetricServiceClient(); + * $formattedName = MetricServiceClient::formatMonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"); + * $response = $metricServiceClient->getMonitoredResourceDescriptor($formattedName); + * } finally { + * $metricServiceClient->close(); + * } + * ``` + * + * @param string $name The monitored resource descriptor to get. The format is + * `"projects/{project_id_or_number}/monitoredResourceDescriptors/{resource_type}"`. + * The `{resource_type}` is a predefined type, such as + * `cloudsql_database`. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Api\MonitoredResourceDescriptor + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getMonitoredResourceDescriptor($name, $optionalArgs = []) + { + $request = new GetMonitoredResourceDescriptorRequest(); + $request->setName($name); + + $mergedSettings = $this->defaultCallSettings['getMonitoredResourceDescriptor']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricServiceStub, + 'GetMonitoredResourceDescriptor', + $mergedSettings, + $this->descriptors['getMonitoredResourceDescriptor'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists metric descriptors that match a filter. This method does not require a Stackdriver account. + * + * Sample code: + * ``` + * try { + * $metricServiceClient = new MetricServiceClient(); + * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $metricServiceClient->listMetricDescriptors($formattedName); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $metricServiceClient->listMetricDescriptors($formattedName, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $metricServiceClient->close(); + * } + * ``` + * + * @param string $name The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param array $optionalArgs { + * Optional. + * + * @type string $filter + * If this field is empty, all custom and + * system-defined metric descriptors are returned. + * Otherwise, the [filter](https://cloud.google.com/monitoring/api/v3/filters) + * specifies which metric descriptors are to be + * returned. For example, the following filter matches all + * [custom metrics](https://cloud.google.com/monitoring/custom-metrics): + * + * metric.type = starts_with("custom.googleapis.com/") + * @type int $pageSize + * The maximum number of resources contained in the underlying API + * response. The API may return fewer values in a page, even if + * there are additional values to be retrieved. + * @type string $pageToken + * A page token is used to specify a page of values to be returned. + * If no page token is specified (the default), the first page + * of values will be returned. Any page token used here must have + * been generated by a previous call to the API. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listMetricDescriptors($name, $optionalArgs = []) + { + $request = new ListMetricDescriptorsRequest(); + $request->setName($name); + if (isset($optionalArgs['filter'])) { + $request->setFilter($optionalArgs['filter']); + } + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listMetricDescriptors']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricServiceStub, + 'ListMetricDescriptors', + $mergedSettings, + $this->descriptors['listMetricDescriptors'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets a single metric descriptor. This method does not require a Stackdriver account. + * + * Sample code: + * ``` + * try { + * $metricServiceClient = new MetricServiceClient(); + * $formattedName = MetricServiceClient::formatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); + * $response = $metricServiceClient->getMetricDescriptor($formattedName); + * } finally { + * $metricServiceClient->close(); + * } + * ``` + * + * @param string $name The metric descriptor on which to execute the request. The format is + * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. + * An example value of `{metric_id}` is + * `"compute.googleapis.com/instance/disk/read_bytes_count"`. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Api\MetricDescriptor + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getMetricDescriptor($name, $optionalArgs = []) + { + $request = new GetMetricDescriptorRequest(); + $request->setName($name); + + $mergedSettings = $this->defaultCallSettings['getMetricDescriptor']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricServiceStub, + 'GetMetricDescriptor', + $mergedSettings, + $this->descriptors['getMetricDescriptor'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Creates a new metric descriptor. + * User-created metric descriptors define + * [custom metrics](https://cloud.google.com/monitoring/custom-metrics). + * + * Sample code: + * ``` + * try { + * $metricServiceClient = new MetricServiceClient(); + * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); + * $metricDescriptor = new MetricDescriptor(); + * $response = $metricServiceClient->createMetricDescriptor($formattedName, $metricDescriptor); + * } finally { + * $metricServiceClient->close(); + * } + * ``` + * + * @param string $name The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param MetricDescriptor $metricDescriptor The new [custom metric](https://cloud.google.com/monitoring/custom-metrics) + * descriptor. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Api\MetricDescriptor + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createMetricDescriptor($name, $metricDescriptor, $optionalArgs = []) + { + $request = new CreateMetricDescriptorRequest(); + $request->setName($name); + $request->setMetricDescriptor($metricDescriptor); + + $mergedSettings = $this->defaultCallSettings['createMetricDescriptor']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricServiceStub, + 'CreateMetricDescriptor', + $mergedSettings, + $this->descriptors['createMetricDescriptor'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Deletes a metric descriptor. Only user-created + * [custom metrics](https://cloud.google.com/monitoring/custom-metrics) can be deleted. + * + * Sample code: + * ``` + * try { + * $metricServiceClient = new MetricServiceClient(); + * $formattedName = MetricServiceClient::formatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); + * $metricServiceClient->deleteMetricDescriptor($formattedName); + * } finally { + * $metricServiceClient->close(); + * } + * ``` + * + * @param string $name The metric descriptor on which to execute the request. The format is + * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. + * An example of `{metric_id}` is: + * `"custom.googleapis.com/my_test_metric"`. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function deleteMetricDescriptor($name, $optionalArgs = []) + { + $request = new DeleteMetricDescriptorRequest(); + $request->setName($name); + + $mergedSettings = $this->defaultCallSettings['deleteMetricDescriptor']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricServiceStub, + 'DeleteMetricDescriptor', + $mergedSettings, + $this->descriptors['deleteMetricDescriptor'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists time series that match a filter. This method does not require a Stackdriver account. + * + * Sample code: + * ``` + * try { + * $metricServiceClient = new MetricServiceClient(); + * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); + * $filter = ""; + * $interval = new TimeInterval(); + * $view = TimeSeriesView::FULL; + * // Iterate through all elements + * $pagedResponse = $metricServiceClient->listTimeSeries($formattedName, $filter, $interval, $view); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $metricServiceClient->listTimeSeries($formattedName, $filter, $interval, $view, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $metricServiceClient->close(); + * } + * ``` + * + * @param string $name The project on which to execute the request. The format is + * "projects/{project_id_or_number}". + * @param string $filter A [monitoring filter](https://cloud.google.com/monitoring/api/v3/filters) that specifies which time + * series should be returned. The filter must specify a single metric type, + * and can additionally specify metric labels and other information. For + * example: + * + * metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND + * metric.label.instance_name = "my-instance-name" + * @param TimeInterval $interval The time interval for which results should be returned. Only time series + * that contain data points in the specified interval are included + * in the response. + * @param int $view Specifies which information is returned about the time series. + * For allowed values, use constants defined on {@see \Google\Monitoring\V3\ListTimeSeriesRequest_TimeSeriesView} + * @param array $optionalArgs { + * Optional. + * + * @type Aggregation $aggregation + * By default, the raw time series data is returned. + * Use this field to combine multiple time series for different + * views of the data. + * @type string $orderBy + * Specifies the order in which the points of the time series should + * be returned. By default, results are not ordered. Currently, + * this field must be left blank. + * @type int $pageSize + * The maximum number of resources contained in the underlying API + * response. The API may return fewer values in a page, even if + * there are additional values to be retrieved. + * @type string $pageToken + * A page token is used to specify a page of values to be returned. + * If no page token is specified (the default), the first page + * of values will be returned. Any page token used here must have + * been generated by a previous call to the API. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listTimeSeries($name, $filter, $interval, $view, $optionalArgs = []) + { + $request = new ListTimeSeriesRequest(); + $request->setName($name); + $request->setFilter($filter); + $request->setInterval($interval); + $request->setView($view); + if (isset($optionalArgs['aggregation'])) { + $request->setAggregation($optionalArgs['aggregation']); + } + if (isset($optionalArgs['orderBy'])) { + $request->setOrderBy($optionalArgs['orderBy']); + } + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listTimeSeries']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricServiceStub, + 'ListTimeSeries', + $mergedSettings, + $this->descriptors['listTimeSeries'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Creates or adds data to one or more time series. + * The response is empty if all time series in the request were written. + * If any time series could not be written, a corresponding failure message is + * included in the error response. + * + * Sample code: + * ``` + * try { + * $metricServiceClient = new MetricServiceClient(); + * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); + * $timeSeries = []; + * $metricServiceClient->createTimeSeries($formattedName, $timeSeries); + * } finally { + * $metricServiceClient->close(); + * } + * ``` + * + * @param string $name The project on which to execute the request. The format is + * `"projects/{project_id_or_number}"`. + * @param TimeSeries[] $timeSeries The new data to be added to a list of time series. + * Adds at most one data point to each of several time series. The new data + * point must be more recent than any other point in its time series. Each + * `TimeSeries` value must fully specify a unique time series by supplying + * all label values for the metric and the monitored resource. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createTimeSeries($name, $timeSeries, $optionalArgs = []) + { + $request = new CreateTimeSeriesRequest(); + $request->setName($name); + $request->setTimeSeries($timeSeries); + + $mergedSettings = $this->defaultCallSettings['createTimeSeries']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->metricServiceStub, + 'CreateTimeSeries', + $mergedSettings, + $this->descriptors['createTimeSeries'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->metricServiceStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/Monitoring/V3/GroupServiceClient.php b/src/Monitoring/V3/GroupServiceClient.php index e2669101e697..4d9f7b4c7897 100644 --- a/src/Monitoring/V3/GroupServiceClient.php +++ b/src/Monitoring/V3/GroupServiceClient.php @@ -30,789 +30,12 @@ namespace Google\Cloud\Monitoring\V3; -use Google\GAX\AgentHeaderDescriptor; -use Google\GAX\ApiCallable; -use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; -use Google\GAX\GrpcCredentialsHelper; -use Google\GAX\PageStreamingDescriptor; -use Google\GAX\PathTemplate; -use Google\Monitoring\V3\CreateGroupRequest; -use Google\Monitoring\V3\DeleteGroupRequest; -use Google\Monitoring\V3\GetGroupRequest; -use Google\Monitoring\V3\Group; -use Google\Monitoring\V3\GroupServiceGrpcClient; -use Google\Monitoring\V3\ListGroupMembersRequest; -use Google\Monitoring\V3\ListGroupsRequest; -use Google\Monitoring\V3\TimeInterval; -use Google\Monitoring\V3\UpdateGroupRequest; +use Google\Cloud\Monitoring\V3\Gapic\GroupServiceGapicClient; /** - * Service Description: The Group API lets you inspect and manage your - * [groups](https://cloud.google.comgoogle.monitoring.v3.Group). - * - * A group is a named filter that is used to identify - * a collection of monitored resources. Groups are typically used to - * mirror the physical and/or logical topology of the environment. - * Because group membership is computed dynamically, monitored - * resources that are started in the future are automatically placed - * in matching groups. By using a group to name monitored resources in, - * for example, an alert policy, the target of that alert policy is - * updated automatically as monitored resources are added and removed - * from the infrastructure. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $groupServiceClient = new GroupServiceClient(); - * $formattedName = GroupServiceClient::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $groupServiceClient->listGroups($formattedName); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $groupServiceClient->listGroups($formattedName, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $groupServiceClient->close(); - * } - * ``` - * - * Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. - * - * @experimental + * {@inheritdoc} */ -class GroupServiceClient +class GroupServiceClient extends GroupServiceGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'monitoring.googleapis.com'; - - /** - * The default port of the service. - */ - const DEFAULT_SERVICE_PORT = 443; - - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - - /** - * The name of the code generator, to be included in the agent header. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $projectNameTemplate; - private static $groupNameTemplate; - - private $grpcCredentialsHelper; - private $groupServiceStub; - private $scopes; - private $defaultCallSettings; - private $descriptors; - - /** - * Formats a string containing the fully-qualified path to represent - * a project resource. - * - * @param string $project - * - * @return string The formatted project resource. - * @experimental - */ - public static function formatProjectName($project) - { - return self::getProjectNameTemplate()->render([ - 'project' => $project, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a group resource. - * - * @param string $project - * @param string $group - * - * @return string The formatted group resource. - * @experimental - */ - public static function formatGroupName($project, $group) - { - return self::getGroupNameTemplate()->render([ - 'project' => $project, - 'group' => $group, - ]); - } - - /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - * - * @param string $projectName The fully-qualified project resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromProjectName($projectName) - { - return self::getProjectNameTemplate()->match($projectName)['project']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a group resource. - * - * @param string $groupName The fully-qualified group resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromGroupName($groupName) - { - return self::getGroupNameTemplate()->match($groupName)['project']; - } - - /** - * Parses the group from the given fully-qualified path which - * represents a group resource. - * - * @param string $groupName The fully-qualified group resource. - * - * @return string The extracted group value. - * @experimental - */ - public static function parseGroupFromGroupName($groupName) - { - return self::getGroupNameTemplate()->match($groupName)['group']; - } - - private static function getProjectNameTemplate() - { - if (self::$projectNameTemplate == null) { - self::$projectNameTemplate = new PathTemplate('projects/{project}'); - } - - return self::$projectNameTemplate; - } - - private static function getGroupNameTemplate() - { - if (self::$groupNameTemplate == null) { - self::$groupNameTemplate = new PathTemplate('projects/{project}/groups/{group}'); - } - - return self::$groupNameTemplate; - } - - private static function getPageStreamingDescriptors() - { - $listGroupsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getGroup', - ]); - $listGroupMembersPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getMembers', - ]); - - $pageStreamingDescriptors = [ - 'listGroups' => $listGroupsPageStreamingDescriptor, - 'listGroupMembers' => $listGroupMembersPageStreamingDescriptor, - ]; - - return $pageStreamingDescriptors; - } - - private static function getGapicVersion() - { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'monitoring.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Stackdriver Monitoring API. - * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read', - 'https://www.googleapis.com/auth/monitoring.write', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'listGroups' => $defaultDescriptors, - 'getGroup' => $defaultDescriptors, - 'createGroup' => $defaultDescriptors, - 'updateGroup' => $defaultDescriptors, - 'deleteGroup' => $defaultDescriptors, - 'listGroupMembers' => $defaultDescriptors, - ]; - $pageStreamingDescriptors = self::getPageStreamingDescriptors(); - foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { - $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/group_service_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.monitoring.v3.GroupService', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createGroupServiceStubFunction = function ($hostname, $opts) { - return new GroupServiceGrpcClient($hostname, $opts); - }; - if (array_key_exists('createGroupServiceStubFunction', $options)) { - $createGroupServiceStubFunction = $options['createGroupServiceStubFunction']; - } - $this->groupServiceStub = $this->grpcCredentialsHelper->createStub( - $createGroupServiceStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Lists the existing groups. - * - * Sample code: - * ``` - * try { - * $groupServiceClient = new GroupServiceClient(); - * $formattedName = GroupServiceClient::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $groupServiceClient->listGroups($formattedName); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $groupServiceClient->listGroups($formattedName, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $groupServiceClient->close(); - * } - * ``` - * - * @param string $name The project whose groups are to be listed. The format is - * `"projects/{project_id_or_number}"`. - * @param array $optionalArgs { - * Optional. - * - * @type string $childrenOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups whose `parentName` field contains the group - * name. If no groups have this parent, the results are empty. - * @type string $ancestorsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups that are ancestors of the specified group. - * The groups are returned in order, starting with the immediate parent and - * ending with the most distant ancestor. If the specified group has no - * immediate parent, the results are empty. - * @type string $descendantsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns the descendants of the specified group. This is a superset of - * the results returned by the `childrenOfGroup` filter, and includes - * children-of-children, and so forth. - * @type int $pageSize - * The maximum number of resources contained in the underlying API - * response. The API may return fewer values in a page, even if - * there are additional values to be retrieved. - * @type string $pageToken - * A page token is used to specify a page of values to be returned. - * If no page token is specified (the default), the first page - * of values will be returned. Any page token used here must have - * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listGroups($name, $optionalArgs = []) - { - $request = new ListGroupsRequest(); - $request->setName($name); - if (isset($optionalArgs['childrenOfGroup'])) { - $request->setChildrenOfGroup($optionalArgs['childrenOfGroup']); - } - if (isset($optionalArgs['ancestorsOfGroup'])) { - $request->setAncestorsOfGroup($optionalArgs['ancestorsOfGroup']); - } - if (isset($optionalArgs['descendantsOfGroup'])) { - $request->setDescendantsOfGroup($optionalArgs['descendantsOfGroup']); - } - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listGroups']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->groupServiceStub, - 'ListGroups', - $mergedSettings, - $this->descriptors['listGroups'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets a single group. - * - * Sample code: - * ``` - * try { - * $groupServiceClient = new GroupServiceClient(); - * $formattedName = GroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); - * $response = $groupServiceClient->getGroup($formattedName); - * } finally { - * $groupServiceClient->close(); - * } - * ``` - * - * @param string $name The group to retrieve. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Monitoring\V3\Group - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getGroup($name, $optionalArgs = []) - { - $request = new GetGroupRequest(); - $request->setName($name); - - $mergedSettings = $this->defaultCallSettings['getGroup']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->groupServiceStub, - 'GetGroup', - $mergedSettings, - $this->descriptors['getGroup'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Creates a new group. - * - * Sample code: - * ``` - * try { - * $groupServiceClient = new GroupServiceClient(); - * $formattedName = GroupServiceClient::formatProjectName("[PROJECT]"); - * $group = new Group(); - * $response = $groupServiceClient->createGroup($formattedName, $group); - * } finally { - * $groupServiceClient->close(); - * } - * ``` - * - * @param string $name The project in which to create the group. The format is - * `"projects/{project_id_or_number}"`. - * @param Group $group A group definition. It is an error to define the `name` field because - * the system assigns the name. - * @param array $optionalArgs { - * Optional. - * - * @type bool $validateOnly - * If true, validate this request but do not create the group. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Monitoring\V3\Group - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createGroup($name, $group, $optionalArgs = []) - { - $request = new CreateGroupRequest(); - $request->setName($name); - $request->setGroup($group); - if (isset($optionalArgs['validateOnly'])) { - $request->setValidateOnly($optionalArgs['validateOnly']); - } - - $mergedSettings = $this->defaultCallSettings['createGroup']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->groupServiceStub, - 'CreateGroup', - $mergedSettings, - $this->descriptors['createGroup'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Updates an existing group. - * You can change any group attributes except `name`. - * - * Sample code: - * ``` - * try { - * $groupServiceClient = new GroupServiceClient(); - * $group = new Group(); - * $response = $groupServiceClient->updateGroup($group); - * } finally { - * $groupServiceClient->close(); - * } - * ``` - * - * @param Group $group The new definition of the group. All fields of the existing group, - * excepting `name`, are replaced with the corresponding fields of this group. - * @param array $optionalArgs { - * Optional. - * - * @type bool $validateOnly - * If true, validate this request but do not update the existing group. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Monitoring\V3\Group - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function updateGroup($group, $optionalArgs = []) - { - $request = new UpdateGroupRequest(); - $request->setGroup($group); - if (isset($optionalArgs['validateOnly'])) { - $request->setValidateOnly($optionalArgs['validateOnly']); - } - - $mergedSettings = $this->defaultCallSettings['updateGroup']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->groupServiceStub, - 'UpdateGroup', - $mergedSettings, - $this->descriptors['updateGroup'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Deletes an existing group. - * - * Sample code: - * ``` - * try { - * $groupServiceClient = new GroupServiceClient(); - * $formattedName = GroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); - * $groupServiceClient->deleteGroup($formattedName); - * } finally { - * $groupServiceClient->close(); - * } - * ``` - * - * @param string $name The group to delete. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function deleteGroup($name, $optionalArgs = []) - { - $request = new DeleteGroupRequest(); - $request->setName($name); - - $mergedSettings = $this->defaultCallSettings['deleteGroup']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->groupServiceStub, - 'DeleteGroup', - $mergedSettings, - $this->descriptors['deleteGroup'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists the monitored resources that are members of a group. - * - * Sample code: - * ``` - * try { - * $groupServiceClient = new GroupServiceClient(); - * $formattedName = GroupServiceClient::formatGroupName("[PROJECT]", "[GROUP]"); - * // Iterate through all elements - * $pagedResponse = $groupServiceClient->listGroupMembers($formattedName); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $groupServiceClient->listGroupMembers($formattedName, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $groupServiceClient->close(); - * } - * ``` - * - * @param string $name The group whose members are listed. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @param array $optionalArgs { - * Optional. - * - * @type int $pageSize - * The maximum number of resources contained in the underlying API - * response. The API may return fewer values in a page, even if - * there are additional values to be retrieved. - * @type string $pageToken - * A page token is used to specify a page of values to be returned. - * If no page token is specified (the default), the first page - * of values will be returned. Any page token used here must have - * been generated by a previous call to the API. - * @type string $filter - * An optional [list filter](https://cloud.google.com/monitoring/api/learn_more#filtering) describing - * the members to be returned. The filter may reference the type, labels, and - * metadata of monitored resources that comprise the group. - * For example, to return only resources representing Compute Engine VM - * instances, use this filter: - * - * resource.type = "gce_instance" - * @type TimeInterval $interval - * An optional time interval for which results should be returned. Only - * members that were part of the group during the specified interval are - * included in the response. If no interval is provided then the group - * membership over the last minute is returned. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listGroupMembers($name, $optionalArgs = []) - { - $request = new ListGroupMembersRequest(); - $request->setName($name); - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - if (isset($optionalArgs['filter'])) { - $request->setFilter($optionalArgs['filter']); - } - if (isset($optionalArgs['interval'])) { - $request->setInterval($optionalArgs['interval']); - } - - $mergedSettings = $this->defaultCallSettings['listGroupMembers']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->groupServiceStub, - 'ListGroupMembers', - $mergedSettings, - $this->descriptors['listGroupMembers'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->groupServiceStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see GroupServiceClientImpl} class. } diff --git a/src/Monitoring/V3/MetricServiceClient.php b/src/Monitoring/V3/MetricServiceClient.php index add715ba45a8..71c27fac3c5b 100644 --- a/src/Monitoring/V3/MetricServiceClient.php +++ b/src/Monitoring/V3/MetricServiceClient.php @@ -30,1003 +30,12 @@ namespace Google\Cloud\Monitoring\V3; -use Google\Api\MetricDescriptor; -use Google\GAX\AgentHeaderDescriptor; -use Google\GAX\ApiCallable; -use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; -use Google\GAX\GrpcCredentialsHelper; -use Google\GAX\PageStreamingDescriptor; -use Google\GAX\PathTemplate; -use Google\Monitoring\V3\Aggregation; -use Google\Monitoring\V3\CreateMetricDescriptorRequest; -use Google\Monitoring\V3\CreateTimeSeriesRequest; -use Google\Monitoring\V3\DeleteMetricDescriptorRequest; -use Google\Monitoring\V3\GetMetricDescriptorRequest; -use Google\Monitoring\V3\GetMonitoredResourceDescriptorRequest; -use Google\Monitoring\V3\ListMetricDescriptorsRequest; -use Google\Monitoring\V3\ListMonitoredResourceDescriptorsRequest; -use Google\Monitoring\V3\ListTimeSeriesRequest; -use Google\Monitoring\V3\ListTimeSeriesRequest_TimeSeriesView as TimeSeriesView; -use Google\Monitoring\V3\MetricServiceGrpcClient; -use Google\Monitoring\V3\TimeInterval; -use Google\Monitoring\V3\TimeSeries; +use Google\Cloud\Monitoring\V3\Gapic\MetricServiceGapicClient; /** - * Service Description: Manages metric descriptors, monitored resource descriptors, and - * time series data. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $metricServiceClient->listMonitoredResourceDescriptors($formattedName); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $metricServiceClient->listMonitoredResourceDescriptors($formattedName, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $metricServiceClient->close(); - * } - * ``` - * - * Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. - * - * @experimental + * {@inheritdoc} */ -class MetricServiceClient +class MetricServiceClient extends MetricServiceGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'monitoring.googleapis.com'; - - /** - * The default port of the service. - */ - const DEFAULT_SERVICE_PORT = 443; - - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - - /** - * The name of the code generator, to be included in the agent header. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $projectNameTemplate; - private static $metricDescriptorNameTemplate; - private static $monitoredResourceDescriptorNameTemplate; - - private $grpcCredentialsHelper; - private $metricServiceStub; - private $scopes; - private $defaultCallSettings; - private $descriptors; - - /** - * Formats a string containing the fully-qualified path to represent - * a project resource. - * - * @param string $project - * - * @return string The formatted project resource. - * @experimental - */ - public static function formatProjectName($project) - { - return self::getProjectNameTemplate()->render([ - 'project' => $project, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a metric_descriptor resource. - * - * @param string $project - * @param string $metricDescriptor - * - * @return string The formatted metric_descriptor resource. - * @experimental - */ - public static function formatMetricDescriptorName($project, $metricDescriptor) - { - return self::getMetricDescriptorNameTemplate()->render([ - 'project' => $project, - 'metric_descriptor' => $metricDescriptor, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a monitored_resource_descriptor resource. - * - * @param string $project - * @param string $monitoredResourceDescriptor - * - * @return string The formatted monitored_resource_descriptor resource. - * @experimental - */ - public static function formatMonitoredResourceDescriptorName($project, $monitoredResourceDescriptor) - { - return self::getMonitoredResourceDescriptorNameTemplate()->render([ - 'project' => $project, - 'monitored_resource_descriptor' => $monitoredResourceDescriptor, - ]); - } - - /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - * - * @param string $projectName The fully-qualified project resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromProjectName($projectName) - { - return self::getProjectNameTemplate()->match($projectName)['project']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a metric_descriptor resource. - * - * @param string $metricDescriptorName The fully-qualified metric_descriptor resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromMetricDescriptorName($metricDescriptorName) - { - return self::getMetricDescriptorNameTemplate()->match($metricDescriptorName)['project']; - } - - /** - * Parses the metric_descriptor from the given fully-qualified path which - * represents a metric_descriptor resource. - * - * @param string $metricDescriptorName The fully-qualified metric_descriptor resource. - * - * @return string The extracted metric_descriptor value. - * @experimental - */ - public static function parseMetricDescriptorFromMetricDescriptorName($metricDescriptorName) - { - return self::getMetricDescriptorNameTemplate()->match($metricDescriptorName)['metric_descriptor']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a monitored_resource_descriptor resource. - * - * @param string $monitoredResourceDescriptorName The fully-qualified monitored_resource_descriptor resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromMonitoredResourceDescriptorName($monitoredResourceDescriptorName) - { - return self::getMonitoredResourceDescriptorNameTemplate()->match($monitoredResourceDescriptorName)['project']; - } - - /** - * Parses the monitored_resource_descriptor from the given fully-qualified path which - * represents a monitored_resource_descriptor resource. - * - * @param string $monitoredResourceDescriptorName The fully-qualified monitored_resource_descriptor resource. - * - * @return string The extracted monitored_resource_descriptor value. - * @experimental - */ - public static function parseMonitoredResourceDescriptorFromMonitoredResourceDescriptorName($monitoredResourceDescriptorName) - { - return self::getMonitoredResourceDescriptorNameTemplate()->match($monitoredResourceDescriptorName)['monitored_resource_descriptor']; - } - - private static function getProjectNameTemplate() - { - if (self::$projectNameTemplate == null) { - self::$projectNameTemplate = new PathTemplate('projects/{project}'); - } - - return self::$projectNameTemplate; - } - - private static function getMetricDescriptorNameTemplate() - { - if (self::$metricDescriptorNameTemplate == null) { - self::$metricDescriptorNameTemplate = new PathTemplate('projects/{project}/metricDescriptors/{metric_descriptor=**}'); - } - - return self::$metricDescriptorNameTemplate; - } - - private static function getMonitoredResourceDescriptorNameTemplate() - { - if (self::$monitoredResourceDescriptorNameTemplate == null) { - self::$monitoredResourceDescriptorNameTemplate = new PathTemplate('projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}'); - } - - return self::$monitoredResourceDescriptorNameTemplate; - } - - private static function getPageStreamingDescriptors() - { - $listMonitoredResourceDescriptorsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getResourceDescriptors', - ]); - $listMetricDescriptorsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getMetricDescriptors', - ]); - $listTimeSeriesPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getTimeSeries', - ]); - - $pageStreamingDescriptors = [ - 'listMonitoredResourceDescriptors' => $listMonitoredResourceDescriptorsPageStreamingDescriptor, - 'listMetricDescriptors' => $listMetricDescriptorsPageStreamingDescriptor, - 'listTimeSeries' => $listTimeSeriesPageStreamingDescriptor, - ]; - - return $pageStreamingDescriptors; - } - - private static function getGapicVersion() - { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'monitoring.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Stackdriver Monitoring API. - * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read', - 'https://www.googleapis.com/auth/monitoring.write', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'listMonitoredResourceDescriptors' => $defaultDescriptors, - 'getMonitoredResourceDescriptor' => $defaultDescriptors, - 'listMetricDescriptors' => $defaultDescriptors, - 'getMetricDescriptor' => $defaultDescriptors, - 'createMetricDescriptor' => $defaultDescriptors, - 'deleteMetricDescriptor' => $defaultDescriptors, - 'listTimeSeries' => $defaultDescriptors, - 'createTimeSeries' => $defaultDescriptors, - ]; - $pageStreamingDescriptors = self::getPageStreamingDescriptors(); - foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { - $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/metric_service_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.monitoring.v3.MetricService', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createMetricServiceStubFunction = function ($hostname, $opts) { - return new MetricServiceGrpcClient($hostname, $opts); - }; - if (array_key_exists('createMetricServiceStubFunction', $options)) { - $createMetricServiceStubFunction = $options['createMetricServiceStubFunction']; - } - $this->metricServiceStub = $this->grpcCredentialsHelper->createStub( - $createMetricServiceStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. - * - * Sample code: - * ``` - * try { - * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $metricServiceClient->listMonitoredResourceDescriptors($formattedName); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $metricServiceClient->listMonitoredResourceDescriptors($formattedName, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $metricServiceClient->close(); - * } - * ``` - * - * @param string $name The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param array $optionalArgs { - * Optional. - * - * @type string $filter - * An optional [filter](https://cloud.google.com/monitoring/api/v3/filters) describing - * the descriptors to be returned. The filter can reference - * the descriptor's type and labels. For example, the - * following filter returns only Google Compute Engine descriptors - * that have an `id` label: - * - * resource.type = starts_with("gce_") AND resource.label:id - * @type int $pageSize - * The maximum number of resources contained in the underlying API - * response. The API may return fewer values in a page, even if - * there are additional values to be retrieved. - * @type string $pageToken - * A page token is used to specify a page of values to be returned. - * If no page token is specified (the default), the first page - * of values will be returned. Any page token used here must have - * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listMonitoredResourceDescriptors($name, $optionalArgs = []) - { - $request = new ListMonitoredResourceDescriptorsRequest(); - $request->setName($name); - if (isset($optionalArgs['filter'])) { - $request->setFilter($optionalArgs['filter']); - } - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listMonitoredResourceDescriptors']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricServiceStub, - 'ListMonitoredResourceDescriptors', - $mergedSettings, - $this->descriptors['listMonitoredResourceDescriptors'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets a single monitored resource descriptor. This method does not require a Stackdriver account. - * - * Sample code: - * ``` - * try { - * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatMonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"); - * $response = $metricServiceClient->getMonitoredResourceDescriptor($formattedName); - * } finally { - * $metricServiceClient->close(); - * } - * ``` - * - * @param string $name The monitored resource descriptor to get. The format is - * `"projects/{project_id_or_number}/monitoredResourceDescriptors/{resource_type}"`. - * The `{resource_type}` is a predefined type, such as - * `cloudsql_database`. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Api\MonitoredResourceDescriptor - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getMonitoredResourceDescriptor($name, $optionalArgs = []) - { - $request = new GetMonitoredResourceDescriptorRequest(); - $request->setName($name); - - $mergedSettings = $this->defaultCallSettings['getMonitoredResourceDescriptor']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricServiceStub, - 'GetMonitoredResourceDescriptor', - $mergedSettings, - $this->descriptors['getMonitoredResourceDescriptor'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists metric descriptors that match a filter. This method does not require a Stackdriver account. - * - * Sample code: - * ``` - * try { - * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $metricServiceClient->listMetricDescriptors($formattedName); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $metricServiceClient->listMetricDescriptors($formattedName, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $metricServiceClient->close(); - * } - * ``` - * - * @param string $name The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param array $optionalArgs { - * Optional. - * - * @type string $filter - * If this field is empty, all custom and - * system-defined metric descriptors are returned. - * Otherwise, the [filter](https://cloud.google.com/monitoring/api/v3/filters) - * specifies which metric descriptors are to be - * returned. For example, the following filter matches all - * [custom metrics](https://cloud.google.com/monitoring/custom-metrics): - * - * metric.type = starts_with("custom.googleapis.com/") - * @type int $pageSize - * The maximum number of resources contained in the underlying API - * response. The API may return fewer values in a page, even if - * there are additional values to be retrieved. - * @type string $pageToken - * A page token is used to specify a page of values to be returned. - * If no page token is specified (the default), the first page - * of values will be returned. Any page token used here must have - * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listMetricDescriptors($name, $optionalArgs = []) - { - $request = new ListMetricDescriptorsRequest(); - $request->setName($name); - if (isset($optionalArgs['filter'])) { - $request->setFilter($optionalArgs['filter']); - } - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listMetricDescriptors']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricServiceStub, - 'ListMetricDescriptors', - $mergedSettings, - $this->descriptors['listMetricDescriptors'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets a single metric descriptor. This method does not require a Stackdriver account. - * - * Sample code: - * ``` - * try { - * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); - * $response = $metricServiceClient->getMetricDescriptor($formattedName); - * } finally { - * $metricServiceClient->close(); - * } - * ``` - * - * @param string $name The metric descriptor on which to execute the request. The format is - * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. - * An example value of `{metric_id}` is - * `"compute.googleapis.com/instance/disk/read_bytes_count"`. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Api\MetricDescriptor - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getMetricDescriptor($name, $optionalArgs = []) - { - $request = new GetMetricDescriptorRequest(); - $request->setName($name); - - $mergedSettings = $this->defaultCallSettings['getMetricDescriptor']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricServiceStub, - 'GetMetricDescriptor', - $mergedSettings, - $this->descriptors['getMetricDescriptor'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Creates a new metric descriptor. - * User-created metric descriptors define - * [custom metrics](https://cloud.google.com/monitoring/custom-metrics). - * - * Sample code: - * ``` - * try { - * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); - * $metricDescriptor = new MetricDescriptor(); - * $response = $metricServiceClient->createMetricDescriptor($formattedName, $metricDescriptor); - * } finally { - * $metricServiceClient->close(); - * } - * ``` - * - * @param string $name The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param MetricDescriptor $metricDescriptor The new [custom metric](https://cloud.google.com/monitoring/custom-metrics) - * descriptor. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Api\MetricDescriptor - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createMetricDescriptor($name, $metricDescriptor, $optionalArgs = []) - { - $request = new CreateMetricDescriptorRequest(); - $request->setName($name); - $request->setMetricDescriptor($metricDescriptor); - - $mergedSettings = $this->defaultCallSettings['createMetricDescriptor']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricServiceStub, - 'CreateMetricDescriptor', - $mergedSettings, - $this->descriptors['createMetricDescriptor'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Deletes a metric descriptor. Only user-created - * [custom metrics](https://cloud.google.com/monitoring/custom-metrics) can be deleted. - * - * Sample code: - * ``` - * try { - * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); - * $metricServiceClient->deleteMetricDescriptor($formattedName); - * } finally { - * $metricServiceClient->close(); - * } - * ``` - * - * @param string $name The metric descriptor on which to execute the request. The format is - * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. - * An example of `{metric_id}` is: - * `"custom.googleapis.com/my_test_metric"`. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function deleteMetricDescriptor($name, $optionalArgs = []) - { - $request = new DeleteMetricDescriptorRequest(); - $request->setName($name); - - $mergedSettings = $this->defaultCallSettings['deleteMetricDescriptor']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricServiceStub, - 'DeleteMetricDescriptor', - $mergedSettings, - $this->descriptors['deleteMetricDescriptor'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists time series that match a filter. This method does not require a Stackdriver account. - * - * Sample code: - * ``` - * try { - * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); - * $filter = ""; - * $interval = new TimeInterval(); - * $view = TimeSeriesView::FULL; - * // Iterate through all elements - * $pagedResponse = $metricServiceClient->listTimeSeries($formattedName, $filter, $interval, $view); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $metricServiceClient->listTimeSeries($formattedName, $filter, $interval, $view, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $metricServiceClient->close(); - * } - * ``` - * - * @param string $name The project on which to execute the request. The format is - * "projects/{project_id_or_number}". - * @param string $filter A [monitoring filter](https://cloud.google.com/monitoring/api/v3/filters) that specifies which time - * series should be returned. The filter must specify a single metric type, - * and can additionally specify metric labels and other information. For - * example: - * - * metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND - * metric.label.instance_name = "my-instance-name" - * @param TimeInterval $interval The time interval for which results should be returned. Only time series - * that contain data points in the specified interval are included - * in the response. - * @param int $view Specifies which information is returned about the time series. - * For allowed values, use constants defined on {@see \Google\Monitoring\V3\ListTimeSeriesRequest_TimeSeriesView} - * @param array $optionalArgs { - * Optional. - * - * @type Aggregation $aggregation - * By default, the raw time series data is returned. - * Use this field to combine multiple time series for different - * views of the data. - * @type string $orderBy - * Specifies the order in which the points of the time series should - * be returned. By default, results are not ordered. Currently, - * this field must be left blank. - * @type int $pageSize - * The maximum number of resources contained in the underlying API - * response. The API may return fewer values in a page, even if - * there are additional values to be retrieved. - * @type string $pageToken - * A page token is used to specify a page of values to be returned. - * If no page token is specified (the default), the first page - * of values will be returned. Any page token used here must have - * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listTimeSeries($name, $filter, $interval, $view, $optionalArgs = []) - { - $request = new ListTimeSeriesRequest(); - $request->setName($name); - $request->setFilter($filter); - $request->setInterval($interval); - $request->setView($view); - if (isset($optionalArgs['aggregation'])) { - $request->setAggregation($optionalArgs['aggregation']); - } - if (isset($optionalArgs['orderBy'])) { - $request->setOrderBy($optionalArgs['orderBy']); - } - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listTimeSeries']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricServiceStub, - 'ListTimeSeries', - $mergedSettings, - $this->descriptors['listTimeSeries'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Creates or adds data to one or more time series. - * The response is empty if all time series in the request were written. - * If any time series could not be written, a corresponding failure message is - * included in the error response. - * - * Sample code: - * ``` - * try { - * $metricServiceClient = new MetricServiceClient(); - * $formattedName = MetricServiceClient::formatProjectName("[PROJECT]"); - * $timeSeries = []; - * $metricServiceClient->createTimeSeries($formattedName, $timeSeries); - * } finally { - * $metricServiceClient->close(); - * } - * ``` - * - * @param string $name The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param TimeSeries[] $timeSeries The new data to be added to a list of time series. - * Adds at most one data point to each of several time series. The new data - * point must be more recent than any other point in its time series. Each - * `TimeSeries` value must fully specify a unique time series by supplying - * all label values for the metric and the monitored resource. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createTimeSeries($name, $timeSeries, $optionalArgs = []) - { - $request = new CreateTimeSeriesRequest(); - $request->setName($name); - $request->setTimeSeries($timeSeries); - - $mergedSettings = $this->defaultCallSettings['createTimeSeries']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->metricServiceStub, - 'CreateTimeSeries', - $mergedSettings, - $this->descriptors['createTimeSeries'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->metricServiceStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see MetricServiceClientImpl} class. } diff --git a/src/Monitoring/composer.json b/src/Monitoring/composer.json index 036f1d8a5174..f0fd72544d12 100644 --- a/src/Monitoring/composer.json +++ b/src/Monitoring/composer.json @@ -5,8 +5,8 @@ "minimum-stability": "stable", "require": { "ext-grpc": "*", - "google/proto-client": "^0.21.0", - "google/gax": "^0.21.0" + "google/proto-client": "^0.22.0", + "google/gax": "^0.22.1" }, "extra": { "component": { diff --git a/src/PubSub/V1/Gapic/PublisherGapicClient.php b/src/PubSub/V1/Gapic/PublisherGapicClient.php new file mode 100644 index 000000000000..5add6e38230c --- /dev/null +++ b/src/PubSub/V1/Gapic/PublisherGapicClient.php @@ -0,0 +1,951 @@ +createTopic($formattedName); + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * Many parameters require resource names to be formatted in a particular way. To assist + * with these names, this class includes a format method for each type of name, and additionally + * a parse method to extract the individual identifiers contained within names that are + * returned. + * + * @experimental + */ +class PublisherGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'pubsub.googleapis.com'; + + /** + * The default port of the service. + */ + const DEFAULT_SERVICE_PORT = 443; + + /** + * The default timeout for non-retrying methods. + */ + const DEFAULT_TIMEOUT_MILLIS = 30000; + + /** + * The name of the code generator, to be included in the agent header. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $projectNameTemplate; + private static $topicNameTemplate; + + protected $grpcCredentialsHelper; + protected $iamPolicyStub; + protected $publisherStub; + private $scopes; + private $defaultCallSettings; + private $descriptors; + + /** + * Formats a string containing the fully-qualified path to represent + * a project resource. + * + * @param string $project + * + * @return string The formatted project resource. + * @experimental + */ + public static function formatProjectName($project) + { + return self::getProjectNameTemplate()->render([ + 'project' => $project, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a topic resource. + * + * @param string $project + * @param string $topic + * + * @return string The formatted topic resource. + * @experimental + */ + public static function formatTopicName($project, $topic) + { + return self::getTopicNameTemplate()->render([ + 'project' => $project, + 'topic' => $topic, + ]); + } + + /** + * Parses the project from the given fully-qualified path which + * represents a project resource. + * + * @param string $projectName The fully-qualified project resource. + * + * @return string The extracted project value. + * @experimental + */ + public static function parseProjectFromProjectName($projectName) + { + return self::getProjectNameTemplate()->match($projectName)['project']; + } + + /** + * Parses the project from the given fully-qualified path which + * represents a topic resource. + * + * @param string $topicName The fully-qualified topic resource. + * + * @return string The extracted project value. + * @experimental + */ + public static function parseProjectFromTopicName($topicName) + { + return self::getTopicNameTemplate()->match($topicName)['project']; + } + + /** + * Parses the topic from the given fully-qualified path which + * represents a topic resource. + * + * @param string $topicName The fully-qualified topic resource. + * + * @return string The extracted topic value. + * @experimental + */ + public static function parseTopicFromTopicName($topicName) + { + return self::getTopicNameTemplate()->match($topicName)['topic']; + } + + private static function getProjectNameTemplate() + { + if (self::$projectNameTemplate == null) { + self::$projectNameTemplate = new PathTemplate('projects/{project}'); + } + + return self::$projectNameTemplate; + } + + private static function getTopicNameTemplate() + { + if (self::$topicNameTemplate == null) { + self::$topicNameTemplate = new PathTemplate('projects/{project}/topics/{topic}'); + } + + return self::$topicNameTemplate; + } + + private static function getPageStreamingDescriptors() + { + $listTopicsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getTopics', + ]); + $listTopicSubscriptionsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getSubscriptions', + ]); + + $pageStreamingDescriptors = [ + 'listTopics' => $listTopicsPageStreamingDescriptor, + 'listTopicSubscriptions' => $listTopicSubscriptionsPageStreamingDescriptor, + ]; + + return $pageStreamingDescriptors; + } + + private static function getGapicVersion() + { + if (file_exists(__DIR__.'/../VERSION')) { + return trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { + return \Google\Cloud\ServiceBuilder::VERSION; + } else { + return; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'pubsub.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * A CredentialsLoader object created using the Google\Auth library. + * @type array $scopes A string array of scopes to use when acquiring credentials. + * Defaults to the scopes for the Google Cloud Pub/Sub API. + * @type array $retryingOverride + * An associative array of string => RetryOptions, where the keys + * are method names (e.g. 'createFoo'), that overrides default retrying + * settings. A value of null indicates that the method in question should + * not retry. + * @type int $timeoutMillis The timeout in milliseconds to use for calls + * that don't use retries. For calls that use retries, + * set the timeout in RetryOptions. + * Default: 30000 (30 seconds) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'createTopic' => $defaultDescriptors, + 'publish' => $defaultDescriptors, + 'getTopic' => $defaultDescriptors, + 'listTopics' => $defaultDescriptors, + 'listTopicSubscriptions' => $defaultDescriptors, + 'deleteTopic' => $defaultDescriptors, + 'setIamPolicy' => $defaultDescriptors, + 'getIamPolicy' => $defaultDescriptors, + 'testIamPermissions' => $defaultDescriptors, + ]; + $pageStreamingDescriptors = self::getPageStreamingDescriptors(); + foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { + $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/publisher_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.pubsub.v1.Publisher', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createIamPolicyStubFunction = function ($hostname, $opts, $channel) { + return new IAMPolicyGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createIamPolicyStubFunction', $options)) { + $createIamPolicyStubFunction = $options['createIamPolicyStubFunction']; + } + $this->iamPolicyStub = $this->grpcCredentialsHelper->createStub($createIamPolicyStubFunction); + $createPublisherStubFunction = function ($hostname, $opts, $channel) { + return new PublisherGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createPublisherStubFunction', $options)) { + $createPublisherStubFunction = $options['createPublisherStubFunction']; + } + $this->publisherStub = $this->grpcCredentialsHelper->createStub($createPublisherStubFunction); + } + + /** + * Creates the given topic with the given name. + * + * Sample code: + * ``` + * try { + * $publisherClient = new PublisherClient(); + * $formattedName = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $response = $publisherClient->createTopic($formattedName); + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * @param string $name The name of the topic. It must have the format + * `"projects/{project}/topics/{topic}"`. `{topic}` must start with a letter, + * and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), + * underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent + * signs (`%`). It must be between 3 and 255 characters in length, and it + * must not start with `"goog"`. + * @param array $optionalArgs { + * Optional. + * + * @type array $labels + * User labels. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Pubsub\V1\Topic + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createTopic($name, $optionalArgs = []) + { + $request = new Topic(); + $request->setName($name); + if (isset($optionalArgs['labels'])) { + $request->setLabels($optionalArgs['labels']); + } + + $mergedSettings = $this->defaultCallSettings['createTopic']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->publisherStub, + 'CreateTopic', + $mergedSettings, + $this->descriptors['createTopic'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic + * does not exist. The message payload must not be empty; it must contain + * either a non-empty data field, or at least one attribute. + * + * Sample code: + * ``` + * try { + * $publisherClient = new PublisherClient(); + * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $data = ""; + * $messagesElement = new PubsubMessage(); + * $messagesElement->setData($data); + * $messages = [$messagesElement]; + * $response = $publisherClient->publish($formattedTopic, $messages); + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * @param string $topic The messages in the request will be published on this topic. + * Format is `projects/{project}/topics/{topic}`. + * @param PubsubMessage[] $messages The messages to publish. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Pubsub\V1\PublishResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function publish($topic, $messages, $optionalArgs = []) + { + $request = new PublishRequest(); + $request->setTopic($topic); + $request->setMessages($messages); + + $mergedSettings = $this->defaultCallSettings['publish']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->publisherStub, + 'Publish', + $mergedSettings, + $this->descriptors['publish'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets the configuration of a topic. + * + * Sample code: + * ``` + * try { + * $publisherClient = new PublisherClient(); + * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $response = $publisherClient->getTopic($formattedTopic); + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * @param string $topic The name of the topic to get. + * Format is `projects/{project}/topics/{topic}`. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Pubsub\V1\Topic + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getTopic($topic, $optionalArgs = []) + { + $request = new GetTopicRequest(); + $request->setTopic($topic); + + $mergedSettings = $this->defaultCallSettings['getTopic']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->publisherStub, + 'GetTopic', + $mergedSettings, + $this->descriptors['getTopic'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists matching topics. + * + * Sample code: + * ``` + * try { + * $publisherClient = new PublisherClient(); + * $formattedProject = PublisherClient::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $publisherClient->listTopics($formattedProject); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $publisherClient->listTopics($formattedProject, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * @param string $project The name of the cloud project that topics belong to. + * Format is `projects/{project}`. + * @param array $optionalArgs { + * Optional. + * + * @type int $pageSize + * The maximum number of resources contained in the underlying API + * response. The API may return fewer values in a page, even if + * there are additional values to be retrieved. + * @type string $pageToken + * A page token is used to specify a page of values to be returned. + * If no page token is specified (the default), the first page + * of values will be returned. Any page token used here must have + * been generated by a previous call to the API. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listTopics($project, $optionalArgs = []) + { + $request = new ListTopicsRequest(); + $request->setProject($project); + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listTopics']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->publisherStub, + 'ListTopics', + $mergedSettings, + $this->descriptors['listTopics'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists the name of the subscriptions for this topic. + * + * Sample code: + * ``` + * try { + * $publisherClient = new PublisherClient(); + * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * // Iterate through all elements + * $pagedResponse = $publisherClient->listTopicSubscriptions($formattedTopic); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $publisherClient->listTopicSubscriptions($formattedTopic, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * @param string $topic The name of the topic that subscriptions are attached to. + * Format is `projects/{project}/topics/{topic}`. + * @param array $optionalArgs { + * Optional. + * + * @type int $pageSize + * The maximum number of resources contained in the underlying API + * response. The API may return fewer values in a page, even if + * there are additional values to be retrieved. + * @type string $pageToken + * A page token is used to specify a page of values to be returned. + * If no page token is specified (the default), the first page + * of values will be returned. Any page token used here must have + * been generated by a previous call to the API. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listTopicSubscriptions($topic, $optionalArgs = []) + { + $request = new ListTopicSubscriptionsRequest(); + $request->setTopic($topic); + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listTopicSubscriptions']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->publisherStub, + 'ListTopicSubscriptions', + $mergedSettings, + $this->descriptors['listTopicSubscriptions'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Deletes the topic with the given name. Returns `NOT_FOUND` if the topic + * does not exist. After a topic is deleted, a new topic may be created with + * the same name; this is an entirely new topic with none of the old + * configuration or subscriptions. Existing subscriptions to this topic are + * not deleted, but their `topic` field is set to `_deleted-topic_`. + * + * Sample code: + * ``` + * try { + * $publisherClient = new PublisherClient(); + * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $publisherClient->deleteTopic($formattedTopic); + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * @param string $topic Name of the topic to delete. + * Format is `projects/{project}/topics/{topic}`. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function deleteTopic($topic, $optionalArgs = []) + { + $request = new DeleteTopicRequest(); + $request->setTopic($topic); + + $mergedSettings = $this->defaultCallSettings['deleteTopic']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->publisherStub, + 'DeleteTopic', + $mergedSettings, + $this->descriptors['deleteTopic'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Sets the access control policy on the specified resource. Replaces any + * existing policy. + * + * Sample code: + * ``` + * try { + * $publisherClient = new PublisherClient(); + * $formattedResource = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $policy = new Policy(); + * $response = $publisherClient->setIamPolicy($formattedResource, $policy); + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * @param string $resource REQUIRED: The resource for which the policy is being specified. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param Policy $policy REQUIRED: The complete policy to be applied to the `resource`. The size of + * the policy is limited to a few 10s of KB. An empty policy is a + * valid policy but certain Cloud Platform services (such as Projects) + * might reject them. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Iam\V1\Policy + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function setIamPolicy($resource, $policy, $optionalArgs = []) + { + $request = new SetIamPolicyRequest(); + $request->setResource($resource); + $request->setPolicy($policy); + + $mergedSettings = $this->defaultCallSettings['setIamPolicy']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->iamPolicyStub, + 'SetIamPolicy', + $mergedSettings, + $this->descriptors['setIamPolicy'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets the access control policy for a resource. + * Returns an empty policy if the resource exists and does not have a policy + * set. + * + * Sample code: + * ``` + * try { + * $publisherClient = new PublisherClient(); + * $formattedResource = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $response = $publisherClient->getIamPolicy($formattedResource); + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * @param string $resource REQUIRED: The resource for which the policy is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Iam\V1\Policy + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getIamPolicy($resource, $optionalArgs = []) + { + $request = new GetIamPolicyRequest(); + $request->setResource($resource); + + $mergedSettings = $this->defaultCallSettings['getIamPolicy']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->iamPolicyStub, + 'GetIamPolicy', + $mergedSettings, + $this->descriptors['getIamPolicy'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Returns permissions that a caller has on the specified resource. + * If the resource does not exist, this will return an empty set of + * permissions, not a NOT_FOUND error. + * + * Sample code: + * ``` + * try { + * $publisherClient = new PublisherClient(); + * $formattedResource = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $permissions = []; + * $response = $publisherClient->testIamPermissions($formattedResource, $permissions); + * } finally { + * $publisherClient->close(); + * } + * ``` + * + * @param string $resource REQUIRED: The resource for which the policy detail is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param string[] $permissions The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see + * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Iam\V1\TestIamPermissionsResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function testIamPermissions($resource, $permissions, $optionalArgs = []) + { + $request = new TestIamPermissionsRequest(); + $request->setResource($resource); + $request->setPermissions($permissions); + + $mergedSettings = $this->defaultCallSettings['testIamPermissions']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->iamPolicyStub, + 'TestIamPermissions', + $mergedSettings, + $this->descriptors['testIamPermissions'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->iamPolicyStub->close(); + $this->publisherStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/PubSub/V1/Gapic/SubscriberGapicClient.php b/src/PubSub/V1/Gapic/SubscriberGapicClient.php new file mode 100644 index 000000000000..52181dca86ea --- /dev/null +++ b/src/PubSub/V1/Gapic/SubscriberGapicClient.php @@ -0,0 +1,1711 @@ +createSubscription($formattedName, $formattedTopic); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * Many parameters require resource names to be formatted in a particular way. To assist + * with these names, this class includes a format method for each type of name, and additionally + * a parse method to extract the individual identifiers contained within names that are + * returned. + * + * @experimental + */ +class SubscriberGapicClient +{ + /** + * The default address of the service. + */ + const SERVICE_ADDRESS = 'pubsub.googleapis.com'; + + /** + * The default port of the service. + */ + const DEFAULT_SERVICE_PORT = 443; + + /** + * The default timeout for non-retrying methods. + */ + const DEFAULT_TIMEOUT_MILLIS = 30000; + + /** + * The name of the code generator, to be included in the agent header. + */ + const CODEGEN_NAME = 'gapic'; + + /** + * The code generator version, to be included in the agent header. + */ + const CODEGEN_VERSION = '0.0.5'; + + private static $projectNameTemplate; + private static $snapshotNameTemplate; + private static $subscriptionNameTemplate; + private static $topicNameTemplate; + + protected $grpcCredentialsHelper; + protected $iamPolicyStub; + protected $subscriberStub; + private $scopes; + private $defaultCallSettings; + private $descriptors; + + /** + * Formats a string containing the fully-qualified path to represent + * a project resource. + * + * @param string $project + * + * @return string The formatted project resource. + * @experimental + */ + public static function formatProjectName($project) + { + return self::getProjectNameTemplate()->render([ + 'project' => $project, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a snapshot resource. + * + * @param string $project + * @param string $snapshot + * + * @return string The formatted snapshot resource. + * @experimental + */ + public static function formatSnapshotName($project, $snapshot) + { + return self::getSnapshotNameTemplate()->render([ + 'project' => $project, + 'snapshot' => $snapshot, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a subscription resource. + * + * @param string $project + * @param string $subscription + * + * @return string The formatted subscription resource. + * @experimental + */ + public static function formatSubscriptionName($project, $subscription) + { + return self::getSubscriptionNameTemplate()->render([ + 'project' => $project, + 'subscription' => $subscription, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent + * a topic resource. + * + * @param string $project + * @param string $topic + * + * @return string The formatted topic resource. + * @experimental + */ + public static function formatTopicName($project, $topic) + { + return self::getTopicNameTemplate()->render([ + 'project' => $project, + 'topic' => $topic, + ]); + } + + /** + * Parses the project from the given fully-qualified path which + * represents a project resource. + * + * @param string $projectName The fully-qualified project resource. + * + * @return string The extracted project value. + * @experimental + */ + public static function parseProjectFromProjectName($projectName) + { + return self::getProjectNameTemplate()->match($projectName)['project']; + } + + /** + * Parses the project from the given fully-qualified path which + * represents a snapshot resource. + * + * @param string $snapshotName The fully-qualified snapshot resource. + * + * @return string The extracted project value. + * @experimental + */ + public static function parseProjectFromSnapshotName($snapshotName) + { + return self::getSnapshotNameTemplate()->match($snapshotName)['project']; + } + + /** + * Parses the snapshot from the given fully-qualified path which + * represents a snapshot resource. + * + * @param string $snapshotName The fully-qualified snapshot resource. + * + * @return string The extracted snapshot value. + * @experimental + */ + public static function parseSnapshotFromSnapshotName($snapshotName) + { + return self::getSnapshotNameTemplate()->match($snapshotName)['snapshot']; + } + + /** + * Parses the project from the given fully-qualified path which + * represents a subscription resource. + * + * @param string $subscriptionName The fully-qualified subscription resource. + * + * @return string The extracted project value. + * @experimental + */ + public static function parseProjectFromSubscriptionName($subscriptionName) + { + return self::getSubscriptionNameTemplate()->match($subscriptionName)['project']; + } + + /** + * Parses the subscription from the given fully-qualified path which + * represents a subscription resource. + * + * @param string $subscriptionName The fully-qualified subscription resource. + * + * @return string The extracted subscription value. + * @experimental + */ + public static function parseSubscriptionFromSubscriptionName($subscriptionName) + { + return self::getSubscriptionNameTemplate()->match($subscriptionName)['subscription']; + } + + /** + * Parses the project from the given fully-qualified path which + * represents a topic resource. + * + * @param string $topicName The fully-qualified topic resource. + * + * @return string The extracted project value. + * @experimental + */ + public static function parseProjectFromTopicName($topicName) + { + return self::getTopicNameTemplate()->match($topicName)['project']; + } + + /** + * Parses the topic from the given fully-qualified path which + * represents a topic resource. + * + * @param string $topicName The fully-qualified topic resource. + * + * @return string The extracted topic value. + * @experimental + */ + public static function parseTopicFromTopicName($topicName) + { + return self::getTopicNameTemplate()->match($topicName)['topic']; + } + + private static function getProjectNameTemplate() + { + if (self::$projectNameTemplate == null) { + self::$projectNameTemplate = new PathTemplate('projects/{project}'); + } + + return self::$projectNameTemplate; + } + + private static function getSnapshotNameTemplate() + { + if (self::$snapshotNameTemplate == null) { + self::$snapshotNameTemplate = new PathTemplate('projects/{project}/snapshots/{snapshot}'); + } + + return self::$snapshotNameTemplate; + } + + private static function getSubscriptionNameTemplate() + { + if (self::$subscriptionNameTemplate == null) { + self::$subscriptionNameTemplate = new PathTemplate('projects/{project}/subscriptions/{subscription}'); + } + + return self::$subscriptionNameTemplate; + } + + private static function getTopicNameTemplate() + { + if (self::$topicNameTemplate == null) { + self::$topicNameTemplate = new PathTemplate('projects/{project}/topics/{topic}'); + } + + return self::$topicNameTemplate; + } + + private static function getPageStreamingDescriptors() + { + $listSubscriptionsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getSubscriptions', + ]); + $listSnapshotsPageStreamingDescriptor = + new PageStreamingDescriptor([ + 'requestPageTokenGetMethod' => 'getPageToken', + 'requestPageTokenSetMethod' => 'setPageToken', + 'requestPageSizeGetMethod' => 'getPageSize', + 'requestPageSizeSetMethod' => 'setPageSize', + 'responsePageTokenGetMethod' => 'getNextPageToken', + 'resourcesGetMethod' => 'getSnapshots', + ]); + + $pageStreamingDescriptors = [ + 'listSubscriptions' => $listSubscriptionsPageStreamingDescriptor, + 'listSnapshots' => $listSnapshotsPageStreamingDescriptor, + ]; + + return $pageStreamingDescriptors; + } + + private static function getGrpcStreamingDescriptors() + { + return [ + 'streamingPull' => [ + 'grpcStreamingType' => 'BidiStreaming', + 'resourcesGetMethod' => 'getReceivedMessages', + ], + ]; + } + + private static function getGapicVersion() + { + if (file_exists(__DIR__.'/../VERSION')) { + return trim(file_get_contents(__DIR__.'/../VERSION')); + } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { + return \Google\Cloud\ServiceBuilder::VERSION; + } else { + return; + } + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $serviceAddress The domain name of the API remote host. + * Default 'pubsub.googleapis.com'. + * @type mixed $port The port on which to connect to the remote host. Default 443. + * @type \Grpc\Channel $channel + * A `Channel` object to be used by gRPC. If not specified, a channel will be constructed. + * @type \Grpc\ChannelCredentials $sslCreds + * A `ChannelCredentials` object for use with an SSL-enabled channel. + * Default: a credentials object returned from + * \Grpc\ChannelCredentials::createSsl() + * NOTE: if the $channel optional argument is specified, then this argument is unused. + * @type bool $forceNewChannel + * If true, this forces gRPC to create a new channel instead of using a persistent channel. + * Defaults to false. + * NOTE: if the $channel optional argument is specified, then this option is unused. + * @type \Google\Auth\CredentialsLoader $credentialsLoader + * A CredentialsLoader object created using the Google\Auth library. + * @type array $scopes A string array of scopes to use when acquiring credentials. + * Defaults to the scopes for the Google Cloud Pub/Sub API. + * @type array $retryingOverride + * An associative array of string => RetryOptions, where the keys + * are method names (e.g. 'createFoo'), that overrides default retrying + * settings. A value of null indicates that the method in question should + * not retry. + * @type int $timeoutMillis The timeout in milliseconds to use for calls + * that don't use retries. For calls that use retries, + * set the timeout in RetryOptions. + * Default: 30000 (30 seconds) + * } + * @experimental + */ + public function __construct($options = []) + { + $defaultOptions = [ + 'serviceAddress' => self::SERVICE_ADDRESS, + 'port' => self::DEFAULT_SERVICE_PORT, + 'scopes' => [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/pubsub', + ], + 'retryingOverride' => null, + 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, + 'libName' => null, + 'libVersion' => null, + ]; + $options = array_merge($defaultOptions, $options); + + $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); + + $headerDescriptor = new AgentHeaderDescriptor([ + 'libName' => $options['libName'], + 'libVersion' => $options['libVersion'], + 'gapicVersion' => $gapicVersion, + ]); + + $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; + $this->descriptors = [ + 'createSubscription' => $defaultDescriptors, + 'getSubscription' => $defaultDescriptors, + 'updateSubscription' => $defaultDescriptors, + 'listSubscriptions' => $defaultDescriptors, + 'deleteSubscription' => $defaultDescriptors, + 'modifyAckDeadline' => $defaultDescriptors, + 'acknowledge' => $defaultDescriptors, + 'pull' => $defaultDescriptors, + 'streamingPull' => $defaultDescriptors, + 'modifyPushConfig' => $defaultDescriptors, + 'listSnapshots' => $defaultDescriptors, + 'createSnapshot' => $defaultDescriptors, + 'deleteSnapshot' => $defaultDescriptors, + 'seek' => $defaultDescriptors, + 'setIamPolicy' => $defaultDescriptors, + 'getIamPolicy' => $defaultDescriptors, + 'testIamPermissions' => $defaultDescriptors, + ]; + $pageStreamingDescriptors = self::getPageStreamingDescriptors(); + foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { + $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; + } + $grpcStreamingDescriptors = self::getGrpcStreamingDescriptors(); + foreach ($grpcStreamingDescriptors as $method => $grpcStreamingDescriptor) { + $this->descriptors[$method]['grpcStreamingDescriptor'] = $grpcStreamingDescriptor; + } + + $clientConfigJsonString = file_get_contents(__DIR__.'/../resources/subscriber_client_config.json'); + $clientConfig = json_decode($clientConfigJsonString, true); + $this->defaultCallSettings = + CallSettings::load( + 'google.pubsub.v1.Subscriber', + $clientConfig, + $options['retryingOverride'], + GrpcConstants::getStatusCodeNames(), + $options['timeoutMillis'] + ); + + $this->scopes = $options['scopes']; + + $createStubOptions = []; + if (array_key_exists('sslCreds', $options)) { + $createStubOptions['sslCreds'] = $options['sslCreds']; + } + $this->grpcCredentialsHelper = new GrpcCredentialsHelper($options); + + $createIamPolicyStubFunction = function ($hostname, $opts, $channel) { + return new IAMPolicyGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createIamPolicyStubFunction', $options)) { + $createIamPolicyStubFunction = $options['createIamPolicyStubFunction']; + } + $this->iamPolicyStub = $this->grpcCredentialsHelper->createStub($createIamPolicyStubFunction); + $createSubscriberStubFunction = function ($hostname, $opts, $channel) { + return new SubscriberGrpcClient($hostname, $opts, $channel); + }; + if (array_key_exists('createSubscriberStubFunction', $options)) { + $createSubscriberStubFunction = $options['createSubscriberStubFunction']; + } + $this->subscriberStub = $this->grpcCredentialsHelper->createStub($createSubscriberStubFunction); + } + + /** + * Creates a subscription to a given topic. + * If the subscription already exists, returns `ALREADY_EXISTS`. + * If the corresponding topic doesn't exist, returns `NOT_FOUND`. + * + * If the name is not provided in the request, the server will assign a random + * name for this subscription on the same project as the topic, conforming + * to the + * [resource name format](https://cloud.google.com/pubsub/docs/overview#names). + * The generated name is populated in the returned Subscription object. + * Note that for REST API requests, you must specify a name in the request. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedName = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $formattedTopic = SubscriberClient::formatTopicName("[PROJECT]", "[TOPIC]"); + * $response = $subscriberClient->createSubscription($formattedName, $formattedTopic); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $name The name of the subscription. It must have the format + * `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must + * start with a letter, and contain only letters (`[A-Za-z]`), numbers + * (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), + * plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters + * in length, and it must not start with `"goog"`. + * @param string $topic The name of the topic from which this subscription is receiving messages. + * Format is `projects/{project}/topics/{topic}`. + * The value of this field will be `_deleted-topic_` if the topic has been + * deleted. + * @param array $optionalArgs { + * Optional. + * + * @type PushConfig $pushConfig + * If push delivery is used with this subscription, this field is + * used to configure it. An empty `pushConfig` signifies that the subscriber + * will pull and ack messages using API methods. + * @type int $ackDeadlineSeconds + * This value is the maximum time after a subscriber receives a message + * before the subscriber should acknowledge the message. After message + * delivery but before the ack deadline expires and before the message is + * acknowledged, it is an outstanding message and will not be delivered + * again during that time (on a best-effort basis). + * + * For pull subscriptions, this value is used as the initial value for the ack + * deadline. To override this value for a given message, call + * `ModifyAckDeadline` with the corresponding `ack_id` if using + * pull. + * The minimum custom deadline you can specify is 10 seconds. + * The maximum custom deadline you can specify is 600 seconds (10 minutes). + * If this parameter is 0, a default value of 10 seconds is used. + * + * For push delivery, this value is also used to set the request timeout for + * the call to the push endpoint. + * + * If the subscriber never acknowledges the message, the Pub/Sub + * system will eventually redeliver the message. + * @type bool $retainAckedMessages + * Indicates whether to retain acknowledged messages. If true, then + * messages are not expunged from the subscription's backlog, even if they are + * acknowledged, until they fall out of the `message_retention_duration` + * window. + * @type Duration $messageRetentionDuration + * How long to retain unacknowledged messages in the subscription's backlog, + * from the moment a message is published. + * If `retain_acked_messages` is true, then this also configures the retention + * of acknowledged messages, and thus configures how far back in time a `Seek` + * can be done. Defaults to 7 days. Cannot be more than 7 days or less than 10 + * minutes. + * @type array $labels + * User labels. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Pubsub\V1\Subscription + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createSubscription($name, $topic, $optionalArgs = []) + { + $request = new Subscription(); + $request->setName($name); + $request->setTopic($topic); + if (isset($optionalArgs['pushConfig'])) { + $request->setPushConfig($optionalArgs['pushConfig']); + } + if (isset($optionalArgs['ackDeadlineSeconds'])) { + $request->setAckDeadlineSeconds($optionalArgs['ackDeadlineSeconds']); + } + if (isset($optionalArgs['retainAckedMessages'])) { + $request->setRetainAckedMessages($optionalArgs['retainAckedMessages']); + } + if (isset($optionalArgs['messageRetentionDuration'])) { + $request->setMessageRetentionDuration($optionalArgs['messageRetentionDuration']); + } + if (isset($optionalArgs['labels'])) { + $request->setLabels($optionalArgs['labels']); + } + + $mergedSettings = $this->defaultCallSettings['createSubscription']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'CreateSubscription', + $mergedSettings, + $this->descriptors['createSubscription'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets the configuration details of a subscription. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $response = $subscriberClient->getSubscription($formattedSubscription); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $subscription The name of the subscription to get. + * Format is `projects/{project}/subscriptions/{sub}`. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Pubsub\V1\Subscription + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getSubscription($subscription, $optionalArgs = []) + { + $request = new GetSubscriptionRequest(); + $request->setSubscription($subscription); + + $mergedSettings = $this->defaultCallSettings['getSubscription']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'GetSubscription', + $mergedSettings, + $this->descriptors['getSubscription'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Updates an existing subscription. Note that certain properties of a + * subscription, such as its topic, are not modifiable. + * NOTE: The style guide requires body: "subscription" instead of body: "*". + * Keeping the latter for internal consistency in V1, however it should be + * corrected in V2. See + * https://cloud.google.com/apis/design/standard_methods#update for details. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $subscription = new Subscription(); + * $updateMask = new FieldMask(); + * $response = $subscriberClient->updateSubscription($subscription, $updateMask); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param Subscription $subscription The updated subscription object. + * @param FieldMask $updateMask Indicates which fields in the provided subscription to update. + * Must be specified and non-empty. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Pubsub\V1\Subscription + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function updateSubscription($subscription, $updateMask, $optionalArgs = []) + { + $request = new UpdateSubscriptionRequest(); + $request->setSubscription($subscription); + $request->setUpdateMask($updateMask); + + $mergedSettings = $this->defaultCallSettings['updateSubscription']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'UpdateSubscription', + $mergedSettings, + $this->descriptors['updateSubscription'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists matching subscriptions. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedProject = SubscriberClient::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $subscriberClient->listSubscriptions($formattedProject); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $subscriberClient->listSubscriptions($formattedProject, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $project The name of the cloud project that subscriptions belong to. + * Format is `projects/{project}`. + * @param array $optionalArgs { + * Optional. + * + * @type int $pageSize + * The maximum number of resources contained in the underlying API + * response. The API may return fewer values in a page, even if + * there are additional values to be retrieved. + * @type string $pageToken + * A page token is used to specify a page of values to be returned. + * If no page token is specified (the default), the first page + * of values will be returned. Any page token used here must have + * been generated by a previous call to the API. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listSubscriptions($project, $optionalArgs = []) + { + $request = new ListSubscriptionsRequest(); + $request->setProject($project); + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listSubscriptions']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'ListSubscriptions', + $mergedSettings, + $this->descriptors['listSubscriptions'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Deletes an existing subscription. All messages retained in the subscription + * are immediately dropped. Calls to `Pull` after deletion will return + * `NOT_FOUND`. After a subscription is deleted, a new one may be created with + * the same name, but the new one has no association with the old + * subscription or its topic unless the same topic is specified. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $subscriberClient->deleteSubscription($formattedSubscription); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $subscription The subscription to delete. + * Format is `projects/{project}/subscriptions/{sub}`. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function deleteSubscription($subscription, $optionalArgs = []) + { + $request = new DeleteSubscriptionRequest(); + $request->setSubscription($subscription); + + $mergedSettings = $this->defaultCallSettings['deleteSubscription']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'DeleteSubscription', + $mergedSettings, + $this->descriptors['deleteSubscription'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Modifies the ack deadline for a specific message. This method is useful + * to indicate that more time is needed to process a message by the + * subscriber, or to make the message available for redelivery if the + * processing was interrupted. Note that this does not modify the + * subscription-level `ackDeadlineSeconds` used for subsequent messages. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $ackIds = []; + * $ackDeadlineSeconds = 0; + * $subscriberClient->modifyAckDeadline($formattedSubscription, $ackIds, $ackDeadlineSeconds); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $subscription The name of the subscription. + * Format is `projects/{project}/subscriptions/{sub}`. + * @param string[] $ackIds List of acknowledgment IDs. + * @param int $ackDeadlineSeconds The new ack deadline with respect to the time this request was sent to + * the Pub/Sub system. For example, if the value is 10, the new + * ack deadline will expire 10 seconds after the `ModifyAckDeadline` call + * was made. Specifying zero may immediately make the message available for + * another pull request. + * The minimum deadline you can specify is 0 seconds. + * The maximum deadline you can specify is 600 seconds (10 minutes). + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function modifyAckDeadline($subscription, $ackIds, $ackDeadlineSeconds, $optionalArgs = []) + { + $request = new ModifyAckDeadlineRequest(); + $request->setSubscription($subscription); + $request->setAckIds($ackIds); + $request->setAckDeadlineSeconds($ackDeadlineSeconds); + + $mergedSettings = $this->defaultCallSettings['modifyAckDeadline']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'ModifyAckDeadline', + $mergedSettings, + $this->descriptors['modifyAckDeadline'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Acknowledges the messages associated with the `ack_ids` in the + * `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages + * from the subscription. + * + * Acknowledging a message whose ack deadline has expired may succeed, + * but such a message may be redelivered later. Acknowledging a message more + * than once will not result in an error. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $ackIds = []; + * $subscriberClient->acknowledge($formattedSubscription, $ackIds); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $subscription The subscription whose message is being acknowledged. + * Format is `projects/{project}/subscriptions/{sub}`. + * @param string[] $ackIds The acknowledgment ID for the messages being acknowledged that was returned + * by the Pub/Sub system in the `Pull` response. Must not be empty. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function acknowledge($subscription, $ackIds, $optionalArgs = []) + { + $request = new AcknowledgeRequest(); + $request->setSubscription($subscription); + $request->setAckIds($ackIds); + + $mergedSettings = $this->defaultCallSettings['acknowledge']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'Acknowledge', + $mergedSettings, + $this->descriptors['acknowledge'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Pulls messages from the server. Returns an empty list if there are no + * messages available in the backlog. The server may return `UNAVAILABLE` if + * there are too many concurrent pull requests pending for the given + * subscription. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $maxMessages = 0; + * $response = $subscriberClient->pull($formattedSubscription, $maxMessages); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $subscription The subscription from which messages should be pulled. + * Format is `projects/{project}/subscriptions/{sub}`. + * @param int $maxMessages The maximum number of messages returned for this request. The Pub/Sub + * system may return fewer than the number specified. + * @param array $optionalArgs { + * Optional. + * + * @type bool $returnImmediately + * If this field set to true, the system will respond immediately even if + * it there are no messages available to return in the `Pull` response. + * Otherwise, the system may wait (for a bounded amount of time) until at + * least one message is available, rather than returning no messages. The + * client may cancel the request if it does not wish to wait any longer for + * the response. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Pubsub\V1\PullResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function pull($subscription, $maxMessages, $optionalArgs = []) + { + $request = new PullRequest(); + $request->setSubscription($subscription); + $request->setMaxMessages($maxMessages); + if (isset($optionalArgs['returnImmediately'])) { + $request->setReturnImmediately($optionalArgs['returnImmediately']); + } + + $mergedSettings = $this->defaultCallSettings['pull']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'Pull', + $mergedSettings, + $this->descriptors['pull'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * (EXPERIMENTAL) StreamingPull is an experimental feature. This RPC will + * respond with UNIMPLEMENTED errors unless you have been invited to test + * this feature. Contact cloud-pubsub@google.com with any questions. + * + * Establishes a stream with the server, which sends messages down to the + * client. The client streams acknowledgements and ack deadline modifications + * back to the server. The server will close the stream and return the status + * on any error. The server may close the stream with status `OK` to reassign + * server-side resources, in which case, the client should re-establish the + * stream. `UNAVAILABLE` may also be returned in the case of a transient error + * (e.g., a server restart). These should also be retried by the client. Flow + * control can be achieved by configuring the underlying RPC channel. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $streamAckDeadlineSeconds = 0; + * $request = new StreamingPullRequest(); + * $request->setSubscription($formattedSubscription); + * $request->setStreamAckDeadlineSeconds($streamAckDeadlineSeconds); + * $requests = [$request]; + * + * // Write all requests to the server, then read all responses until the + * // stream is complete + * $stream = $subscriberClient->streamingPull(); + * $stream->writeAll($requests); + * foreach ($stream->closeWriteAndReadAll() as $element) { + * // doSomethingWith($element); + * } + * + * // OR write requests individually, making read() calls if + * // required. Call closeWrite() once writes are complete, and read the + * // remaining responses from the server. + * $stream = $subscriberClient->streamingPull(); + * foreach ($requests as $request) { + * $stream->write($request); + * // if required, read a single response from the stream + * $element = $stream->read(); + * // doSomethingWith($element) + * } + * $stream->closeWrite(); + * $element = $stream->read(); + * while (!is_null($element)) { + * // doSomethingWith($element) + * $element = $stream->read(); + * } + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param array $optionalArgs { + * Optional. + * + * @type int $timeoutMillis + * Timeout to use for this call. + * } + * + * @return \Google\GAX\BidiStream + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function streamingPull($optionalArgs = []) + { + $mergedSettings = $this->defaultCallSettings['streamingPull']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'StreamingPull', + $mergedSettings, + $this->descriptors['streamingPull'] + ); + + return $callable( + null, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Modifies the `PushConfig` for a specified subscription. + * + * This may be used to change a push subscription to a pull one (signified by + * an empty `PushConfig`) or vice versa, or change the endpoint URL and other + * attributes of a push subscription. Messages will accumulate for delivery + * continuously through the call regardless of changes to the `PushConfig`. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $pushConfig = new PushConfig(); + * $subscriberClient->modifyPushConfig($formattedSubscription, $pushConfig); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $subscription The name of the subscription. + * Format is `projects/{project}/subscriptions/{sub}`. + * @param PushConfig $pushConfig The push configuration for future deliveries. + * + * An empty `pushConfig` indicates that the Pub/Sub system should + * stop pushing messages from the given subscription and allow + * messages to be pulled and acknowledged - effectively pausing + * the subscription if `Pull` is not called. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function modifyPushConfig($subscription, $pushConfig, $optionalArgs = []) + { + $request = new ModifyPushConfigRequest(); + $request->setSubscription($subscription); + $request->setPushConfig($pushConfig); + + $mergedSettings = $this->defaultCallSettings['modifyPushConfig']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'ModifyPushConfig', + $mergedSettings, + $this->descriptors['modifyPushConfig'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Lists the existing snapshots. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedProject = SubscriberClient::formatProjectName("[PROJECT]"); + * // Iterate through all elements + * $pagedResponse = $subscriberClient->listSnapshots($formattedProject); + * foreach ($pagedResponse->iterateAllElements() as $element) { + * // doSomethingWith($element); + * } + * + * // OR iterate over pages of elements, with the maximum page size set to 5 + * $pagedResponse = $subscriberClient->listSnapshots($formattedProject, ['pageSize' => 5]); + * foreach ($pagedResponse->iteratePages() as $page) { + * foreach ($page as $element) { + * // doSomethingWith($element); + * } + * } + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $project The name of the cloud project that snapshots belong to. + * Format is `projects/{project}`. + * @param array $optionalArgs { + * Optional. + * + * @type int $pageSize + * The maximum number of resources contained in the underlying API + * response. The API may return fewer values in a page, even if + * there are additional values to be retrieved. + * @type string $pageToken + * A page token is used to specify a page of values to be returned. + * If no page token is specified (the default), the first page + * of values will be returned. Any page token used here must have + * been generated by a previous call to the API. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\GAX\PagedListResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function listSnapshots($project, $optionalArgs = []) + { + $request = new ListSnapshotsRequest(); + $request->setProject($project); + if (isset($optionalArgs['pageSize'])) { + $request->setPageSize($optionalArgs['pageSize']); + } + if (isset($optionalArgs['pageToken'])) { + $request->setPageToken($optionalArgs['pageToken']); + } + + $mergedSettings = $this->defaultCallSettings['listSnapshots']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'ListSnapshots', + $mergedSettings, + $this->descriptors['listSnapshots'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Creates a snapshot from the requested subscription. + * If the snapshot already exists, returns `ALREADY_EXISTS`. + * If the requested subscription doesn't exist, returns `NOT_FOUND`. + * + * If the name is not provided in the request, the server will assign a random + * name for this snapshot on the same project as the subscription, conforming + * to the + * [resource name format](https://cloud.google.com/pubsub/docs/overview#names). + * The generated name is populated in the returned Snapshot object. + * Note that for REST API requests, you must specify a name in the request. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedName = SubscriberClient::formatSnapshotName("[PROJECT]", "[SNAPSHOT]"); + * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $response = $subscriberClient->createSnapshot($formattedName, $formattedSubscription); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $name Optional user-provided name for this snapshot. + * If the name is not provided in the request, the server will assign a random + * name for this snapshot on the same project as the subscription. + * Note that for REST API requests, you must specify a name. + * Format is `projects/{project}/snapshots/{snap}`. + * @param string $subscription The subscription whose backlog the snapshot retains. + * Specifically, the created snapshot is guaranteed to retain: + * (a) The existing backlog on the subscription. More precisely, this is + * defined as the messages in the subscription's backlog that are + * unacknowledged upon the successful completion of the + * `CreateSnapshot` request; as well as: + * (b) Any messages published to the subscription's topic following the + * successful completion of the CreateSnapshot request. + * Format is `projects/{project}/subscriptions/{sub}`. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Pubsub\V1\Snapshot + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function createSnapshot($name, $subscription, $optionalArgs = []) + { + $request = new CreateSnapshotRequest(); + $request->setName($name); + $request->setSubscription($subscription); + + $mergedSettings = $this->defaultCallSettings['createSnapshot']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'CreateSnapshot', + $mergedSettings, + $this->descriptors['createSnapshot'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Removes an existing snapshot. All messages retained in the snapshot + * are immediately dropped. After a snapshot is deleted, a new one may be + * created with the same name, but the new one has no association with the old + * snapshot or its subscription, unless the same subscription is specified. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedSnapshot = SubscriberClient::formatSnapshotName("[PROJECT]", "[SNAPSHOT]"); + * $subscriberClient->deleteSnapshot($formattedSnapshot); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $snapshot The name of the snapshot to delete. + * Format is `projects/{project}/snapshots/{snap}`. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function deleteSnapshot($snapshot, $optionalArgs = []) + { + $request = new DeleteSnapshotRequest(); + $request->setSnapshot($snapshot); + + $mergedSettings = $this->defaultCallSettings['deleteSnapshot']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'DeleteSnapshot', + $mergedSettings, + $this->descriptors['deleteSnapshot'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Seeks an existing subscription to a point in time or to a given snapshot, + * whichever is provided in the request. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $response = $subscriberClient->seek($formattedSubscription); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $subscription The subscription to affect. + * @param array $optionalArgs { + * Optional. + * + * @type Timestamp $time + * The time to seek to. + * Messages retained in the subscription that were published before this + * time are marked as acknowledged, and messages retained in the + * subscription that were published after this time are marked as + * unacknowledged. Note that this operation affects only those messages + * retained in the subscription (configured by the combination of + * `message_retention_duration` and `retain_acked_messages`). For example, + * if `time` corresponds to a point before the message retention + * window (or to a point before the system's notion of the subscription + * creation time), only retained messages will be marked as unacknowledged, + * and already-expunged messages will not be restored. + * @type string $snapshot + * The snapshot to seek to. The snapshot's topic must be the same as that of + * the provided subscription. + * Format is `projects/{project}/snapshots/{snap}`. + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Pubsub\V1\SeekResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function seek($subscription, $optionalArgs = []) + { + $request = new SeekRequest(); + $request->setSubscription($subscription); + if (isset($optionalArgs['time'])) { + $request->setTime($optionalArgs['time']); + } + if (isset($optionalArgs['snapshot'])) { + $request->setSnapshot($optionalArgs['snapshot']); + } + + $mergedSettings = $this->defaultCallSettings['seek']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->subscriberStub, + 'Seek', + $mergedSettings, + $this->descriptors['seek'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Sets the access control policy on the specified resource. Replaces any + * existing policy. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedResource = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $policy = new Policy(); + * $response = $subscriberClient->setIamPolicy($formattedResource, $policy); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $resource REQUIRED: The resource for which the policy is being specified. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param Policy $policy REQUIRED: The complete policy to be applied to the `resource`. The size of + * the policy is limited to a few 10s of KB. An empty policy is a + * valid policy but certain Cloud Platform services (such as Projects) + * might reject them. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Iam\V1\Policy + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function setIamPolicy($resource, $policy, $optionalArgs = []) + { + $request = new SetIamPolicyRequest(); + $request->setResource($resource); + $request->setPolicy($policy); + + $mergedSettings = $this->defaultCallSettings['setIamPolicy']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->iamPolicyStub, + 'SetIamPolicy', + $mergedSettings, + $this->descriptors['setIamPolicy'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Gets the access control policy for a resource. + * Returns an empty policy if the resource exists and does not have a policy + * set. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedResource = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $response = $subscriberClient->getIamPolicy($formattedResource); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $resource REQUIRED: The resource for which the policy is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Iam\V1\Policy + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function getIamPolicy($resource, $optionalArgs = []) + { + $request = new GetIamPolicyRequest(); + $request->setResource($resource); + + $mergedSettings = $this->defaultCallSettings['getIamPolicy']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->iamPolicyStub, + 'GetIamPolicy', + $mergedSettings, + $this->descriptors['getIamPolicy'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Returns permissions that a caller has on the specified resource. + * If the resource does not exist, this will return an empty set of + * permissions, not a NOT_FOUND error. + * + * Sample code: + * ``` + * try { + * $subscriberClient = new SubscriberClient(); + * $formattedResource = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); + * $permissions = []; + * $response = $subscriberClient->testIamPermissions($formattedResource, $permissions); + * } finally { + * $subscriberClient->close(); + * } + * ``` + * + * @param string $resource REQUIRED: The resource for which the policy detail is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param string[] $permissions The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see + * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). + * @param array $optionalArgs { + * Optional. + * + * @type \Google\GAX\RetrySettings $retrySettings + * Retry settings to use for this call. If present, then + * $timeoutMillis is ignored. + * @type int $timeoutMillis + * Timeout to use for this call. Only used if $retrySettings + * is not set. + * } + * + * @return \Google\Iam\V1\TestIamPermissionsResponse + * + * @throws \Google\GAX\ApiException if the remote call fails + * @experimental + */ + public function testIamPermissions($resource, $permissions, $optionalArgs = []) + { + $request = new TestIamPermissionsRequest(); + $request->setResource($resource); + $request->setPermissions($permissions); + + $mergedSettings = $this->defaultCallSettings['testIamPermissions']->merge( + new CallSettings($optionalArgs) + ); + $callable = ApiCallable::createApiCall( + $this->iamPolicyStub, + 'TestIamPermissions', + $mergedSettings, + $this->descriptors['testIamPermissions'] + ); + + return $callable( + $request, + [], + ['call_credentials_callback' => $this->createCredentialsCallback()]); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new + * calls are immediately cancelled. + * + * @experimental + */ + public function close() + { + $this->iamPolicyStub->close(); + $this->subscriberStub->close(); + } + + private function createCredentialsCallback() + { + return $this->grpcCredentialsHelper->createCallCredentialsCallback(); + } +} diff --git a/src/PubSub/V1/PublisherClient.php b/src/PubSub/V1/PublisherClient.php index cad46c40d935..8b46b6e2dc1a 100644 --- a/src/PubSub/V1/PublisherClient.php +++ b/src/PubSub/V1/PublisherClient.php @@ -30,923 +30,12 @@ namespace Google\Cloud\PubSub\V1; -use Google\GAX\AgentHeaderDescriptor; -use Google\GAX\ApiCallable; -use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; -use Google\GAX\GrpcCredentialsHelper; -use Google\GAX\PageStreamingDescriptor; -use Google\GAX\PathTemplate; -use Google\Iam\V1\GetIamPolicyRequest; -use Google\Iam\V1\IAMPolicyGrpcClient; -use Google\Iam\V1\Policy; -use Google\Iam\V1\SetIamPolicyRequest; -use Google\Iam\V1\TestIamPermissionsRequest; -use Google\Pubsub\V1\DeleteTopicRequest; -use Google\Pubsub\V1\GetTopicRequest; -use Google\Pubsub\V1\ListTopicSubscriptionsRequest; -use Google\Pubsub\V1\ListTopicsRequest; -use Google\Pubsub\V1\PublishRequest; -use Google\Pubsub\V1\PublisherGrpcClient; -use Google\Pubsub\V1\PubsubMessage; -use Google\Pubsub\V1\Topic; +use Google\Cloud\PubSub\V1\Gapic\PublisherGapicClient; /** - * Service Description: The service that an application uses to manipulate topics, and to send - * messages to a topic. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedName = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $response = $publisherClient->createTopic($formattedName); - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. - * - * @experimental + * {@inheritdoc} */ -class PublisherClient +class PublisherClient extends PublisherGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'pubsub.googleapis.com'; - - /** - * The default port of the service. - */ - const DEFAULT_SERVICE_PORT = 443; - - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - - /** - * The name of the code generator, to be included in the agent header. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $projectNameTemplate; - private static $topicNameTemplate; - - private $grpcCredentialsHelper; - private $iamPolicyStub; - private $publisherStub; - private $scopes; - private $defaultCallSettings; - private $descriptors; - - /** - * Formats a string containing the fully-qualified path to represent - * a project resource. - * - * @param string $project - * - * @return string The formatted project resource. - * @experimental - */ - public static function formatProjectName($project) - { - return self::getProjectNameTemplate()->render([ - 'project' => $project, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a topic resource. - * - * @param string $project - * @param string $topic - * - * @return string The formatted topic resource. - * @experimental - */ - public static function formatTopicName($project, $topic) - { - return self::getTopicNameTemplate()->render([ - 'project' => $project, - 'topic' => $topic, - ]); - } - - /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - * - * @param string $projectName The fully-qualified project resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromProjectName($projectName) - { - return self::getProjectNameTemplate()->match($projectName)['project']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a topic resource. - * - * @param string $topicName The fully-qualified topic resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromTopicName($topicName) - { - return self::getTopicNameTemplate()->match($topicName)['project']; - } - - /** - * Parses the topic from the given fully-qualified path which - * represents a topic resource. - * - * @param string $topicName The fully-qualified topic resource. - * - * @return string The extracted topic value. - * @experimental - */ - public static function parseTopicFromTopicName($topicName) - { - return self::getTopicNameTemplate()->match($topicName)['topic']; - } - - private static function getProjectNameTemplate() - { - if (self::$projectNameTemplate == null) { - self::$projectNameTemplate = new PathTemplate('projects/{project}'); - } - - return self::$projectNameTemplate; - } - - private static function getTopicNameTemplate() - { - if (self::$topicNameTemplate == null) { - self::$topicNameTemplate = new PathTemplate('projects/{project}/topics/{topic}'); - } - - return self::$topicNameTemplate; - } - - private static function getPageStreamingDescriptors() - { - $listTopicsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getTopics', - ]); - $listTopicSubscriptionsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getSubscriptions', - ]); - - $pageStreamingDescriptors = [ - 'listTopics' => $listTopicsPageStreamingDescriptor, - 'listTopicSubscriptions' => $listTopicSubscriptionsPageStreamingDescriptor, - ]; - - return $pageStreamingDescriptors; - } - - private static function getGapicVersion() - { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'pubsub.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Google Cloud Pub/Sub API. - * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'createTopic' => $defaultDescriptors, - 'publish' => $defaultDescriptors, - 'getTopic' => $defaultDescriptors, - 'listTopics' => $defaultDescriptors, - 'listTopicSubscriptions' => $defaultDescriptors, - 'deleteTopic' => $defaultDescriptors, - 'setIamPolicy' => $defaultDescriptors, - 'getIamPolicy' => $defaultDescriptors, - 'testIamPermissions' => $defaultDescriptors, - ]; - $pageStreamingDescriptors = self::getPageStreamingDescriptors(); - foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { - $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/publisher_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.pubsub.v1.Publisher', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createIamPolicyStubFunction = function ($hostname, $opts) { - return new IAMPolicyGrpcClient($hostname, $opts); - }; - if (array_key_exists('createIamPolicyStubFunction', $options)) { - $createIamPolicyStubFunction = $options['createIamPolicyStubFunction']; - } - $this->iamPolicyStub = $this->grpcCredentialsHelper->createStub( - $createIamPolicyStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - $createPublisherStubFunction = function ($hostname, $opts) { - return new PublisherGrpcClient($hostname, $opts); - }; - if (array_key_exists('createPublisherStubFunction', $options)) { - $createPublisherStubFunction = $options['createPublisherStubFunction']; - } - $this->publisherStub = $this->grpcCredentialsHelper->createStub( - $createPublisherStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Creates the given topic with the given name. - * - * Sample code: - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedName = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $response = $publisherClient->createTopic($formattedName); - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * @param string $name The name of the topic. It must have the format - * `"projects/{project}/topics/{topic}"`. `{topic}` must start with a letter, - * and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), - * underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent - * signs (`%`). It must be between 3 and 255 characters in length, and it - * must not start with `"goog"`. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Pubsub\V1\Topic - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createTopic($name, $optionalArgs = []) - { - $request = new Topic(); - $request->setName($name); - - $mergedSettings = $this->defaultCallSettings['createTopic']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->publisherStub, - 'CreateTopic', - $mergedSettings, - $this->descriptors['createTopic'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic - * does not exist. The message payload must not be empty; it must contain - * either a non-empty data field, or at least one attribute. - * - * Sample code: - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $data = ""; - * $messagesElement = new PubsubMessage(); - * $messagesElement->setData($data); - * $messages = [$messagesElement]; - * $response = $publisherClient->publish($formattedTopic, $messages); - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * @param string $topic The messages in the request will be published on this topic. - * Format is `projects/{project}/topics/{topic}`. - * @param PubsubMessage[] $messages The messages to publish. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Pubsub\V1\PublishResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function publish($topic, $messages, $optionalArgs = []) - { - $request = new PublishRequest(); - $request->setTopic($topic); - $request->setMessages($messages); - - $mergedSettings = $this->defaultCallSettings['publish']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->publisherStub, - 'Publish', - $mergedSettings, - $this->descriptors['publish'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets the configuration of a topic. - * - * Sample code: - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $response = $publisherClient->getTopic($formattedTopic); - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * @param string $topic The name of the topic to get. - * Format is `projects/{project}/topics/{topic}`. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Pubsub\V1\Topic - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getTopic($topic, $optionalArgs = []) - { - $request = new GetTopicRequest(); - $request->setTopic($topic); - - $mergedSettings = $this->defaultCallSettings['getTopic']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->publisherStub, - 'GetTopic', - $mergedSettings, - $this->descriptors['getTopic'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists matching topics. - * - * Sample code: - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedProject = PublisherClient::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $publisherClient->listTopics($formattedProject); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $publisherClient->listTopics($formattedProject, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * @param string $project The name of the cloud project that topics belong to. - * Format is `projects/{project}`. - * @param array $optionalArgs { - * Optional. - * - * @type int $pageSize - * The maximum number of resources contained in the underlying API - * response. The API may return fewer values in a page, even if - * there are additional values to be retrieved. - * @type string $pageToken - * A page token is used to specify a page of values to be returned. - * If no page token is specified (the default), the first page - * of values will be returned. Any page token used here must have - * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listTopics($project, $optionalArgs = []) - { - $request = new ListTopicsRequest(); - $request->setProject($project); - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listTopics']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->publisherStub, - 'ListTopics', - $mergedSettings, - $this->descriptors['listTopics'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists the name of the subscriptions for this topic. - * - * Sample code: - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * // Iterate through all elements - * $pagedResponse = $publisherClient->listTopicSubscriptions($formattedTopic); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $publisherClient->listTopicSubscriptions($formattedTopic, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * @param string $topic The name of the topic that subscriptions are attached to. - * Format is `projects/{project}/topics/{topic}`. - * @param array $optionalArgs { - * Optional. - * - * @type int $pageSize - * The maximum number of resources contained in the underlying API - * response. The API may return fewer values in a page, even if - * there are additional values to be retrieved. - * @type string $pageToken - * A page token is used to specify a page of values to be returned. - * If no page token is specified (the default), the first page - * of values will be returned. Any page token used here must have - * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listTopicSubscriptions($topic, $optionalArgs = []) - { - $request = new ListTopicSubscriptionsRequest(); - $request->setTopic($topic); - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listTopicSubscriptions']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->publisherStub, - 'ListTopicSubscriptions', - $mergedSettings, - $this->descriptors['listTopicSubscriptions'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Deletes the topic with the given name. Returns `NOT_FOUND` if the topic - * does not exist. After a topic is deleted, a new topic may be created with - * the same name; this is an entirely new topic with none of the old - * configuration or subscriptions. Existing subscriptions to this topic are - * not deleted, but their `topic` field is set to `_deleted-topic_`. - * - * Sample code: - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedTopic = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $publisherClient->deleteTopic($formattedTopic); - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * @param string $topic Name of the topic to delete. - * Format is `projects/{project}/topics/{topic}`. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function deleteTopic($topic, $optionalArgs = []) - { - $request = new DeleteTopicRequest(); - $request->setTopic($topic); - - $mergedSettings = $this->defaultCallSettings['deleteTopic']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->publisherStub, - 'DeleteTopic', - $mergedSettings, - $this->descriptors['deleteTopic'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Sets the access control policy on the specified resource. Replaces any - * existing policy. - * - * Sample code: - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedResource = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $policy = new Policy(); - * $response = $publisherClient->setIamPolicy($formattedResource, $policy); - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * @param string $resource REQUIRED: The resource for which the policy is being specified. - * `resource` is usually specified as a path. For example, a Project - * resource is specified as `projects/{project}`. - * @param Policy $policy REQUIRED: The complete policy to be applied to the `resource`. The size of - * the policy is limited to a few 10s of KB. An empty policy is a - * valid policy but certain Cloud Platform services (such as Projects) - * might reject them. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Iam\V1\Policy - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function setIamPolicy($resource, $policy, $optionalArgs = []) - { - $request = new SetIamPolicyRequest(); - $request->setResource($resource); - $request->setPolicy($policy); - - $mergedSettings = $this->defaultCallSettings['setIamPolicy']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->iamPolicyStub, - 'SetIamPolicy', - $mergedSettings, - $this->descriptors['setIamPolicy'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets the access control policy for a resource. - * Returns an empty policy if the resource exists and does not have a policy - * set. - * - * Sample code: - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedResource = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $response = $publisherClient->getIamPolicy($formattedResource); - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * @param string $resource REQUIRED: The resource for which the policy is being requested. - * `resource` is usually specified as a path. For example, a Project - * resource is specified as `projects/{project}`. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Iam\V1\Policy - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getIamPolicy($resource, $optionalArgs = []) - { - $request = new GetIamPolicyRequest(); - $request->setResource($resource); - - $mergedSettings = $this->defaultCallSettings['getIamPolicy']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->iamPolicyStub, - 'GetIamPolicy', - $mergedSettings, - $this->descriptors['getIamPolicy'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Returns permissions that a caller has on the specified resource. - * If the resource does not exist, this will return an empty set of - * permissions, not a NOT_FOUND error. - * - * Sample code: - * ``` - * try { - * $publisherClient = new PublisherClient(); - * $formattedResource = PublisherClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $permissions = []; - * $response = $publisherClient->testIamPermissions($formattedResource, $permissions); - * } finally { - * $publisherClient->close(); - * } - * ``` - * - * @param string $resource REQUIRED: The resource for which the policy detail is being requested. - * `resource` is usually specified as a path. For example, a Project - * resource is specified as `projects/{project}`. - * @param string[] $permissions The set of permissions to check for the `resource`. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. For more - * information see - * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Iam\V1\TestIamPermissionsResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function testIamPermissions($resource, $permissions, $optionalArgs = []) - { - $request = new TestIamPermissionsRequest(); - $request->setResource($resource); - $request->setPermissions($permissions); - - $mergedSettings = $this->defaultCallSettings['testIamPermissions']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->iamPolicyStub, - 'TestIamPermissions', - $mergedSettings, - $this->descriptors['testIamPermissions'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->iamPolicyStub->close(); - $this->publisherStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see PublisherClientImpl} class. } diff --git a/src/PubSub/V1/SubscriberClient.php b/src/PubSub/V1/SubscriberClient.php index b81cf7c0ad1d..3a80dea17e78 100644 --- a/src/PubSub/V1/SubscriberClient.php +++ b/src/PubSub/V1/SubscriberClient.php @@ -30,1679 +30,12 @@ namespace Google\Cloud\PubSub\V1; -use Google\GAX\AgentHeaderDescriptor; -use Google\GAX\ApiCallable; -use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; -use Google\GAX\GrpcCredentialsHelper; -use Google\GAX\PageStreamingDescriptor; -use Google\GAX\PathTemplate; -use Google\Iam\V1\GetIamPolicyRequest; -use Google\Iam\V1\IAMPolicyGrpcClient; -use Google\Iam\V1\Policy; -use Google\Iam\V1\SetIamPolicyRequest; -use Google\Iam\V1\TestIamPermissionsRequest; -use Google\Protobuf\Duration; -use Google\Protobuf\FieldMask; -use Google\Protobuf\Timestamp; -use Google\Pubsub\V1\AcknowledgeRequest; -use Google\Pubsub\V1\CreateSnapshotRequest; -use Google\Pubsub\V1\DeleteSnapshotRequest; -use Google\Pubsub\V1\DeleteSubscriptionRequest; -use Google\Pubsub\V1\GetSubscriptionRequest; -use Google\Pubsub\V1\ListSnapshotsRequest; -use Google\Pubsub\V1\ListSubscriptionsRequest; -use Google\Pubsub\V1\ModifyAckDeadlineRequest; -use Google\Pubsub\V1\ModifyPushConfigRequest; -use Google\Pubsub\V1\PullRequest; -use Google\Pubsub\V1\PushConfig; -use Google\Pubsub\V1\SeekRequest; -use Google\Pubsub\V1\StreamingPullRequest; -use Google\Pubsub\V1\SubscriberGrpcClient; -use Google\Pubsub\V1\Subscription; -use Google\Pubsub\V1\UpdateSubscriptionRequest; +use Google\Cloud\PubSub\V1\Gapic\SubscriberGapicClient; /** - * Service Description: The service that an application uses to manipulate subscriptions and to - * consume messages from a subscription via the `Pull` method. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedName = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $formattedTopic = SubscriberClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $response = $subscriberClient->createSubscription($formattedName, $formattedTopic); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. - * - * @experimental + * {@inheritdoc} */ -class SubscriberClient +class SubscriberClient extends SubscriberGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'pubsub.googleapis.com'; - - /** - * The default port of the service. - */ - const DEFAULT_SERVICE_PORT = 443; - - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - - /** - * The name of the code generator, to be included in the agent header. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $projectNameTemplate; - private static $snapshotNameTemplate; - private static $subscriptionNameTemplate; - private static $topicNameTemplate; - - private $grpcCredentialsHelper; - private $iamPolicyStub; - private $subscriberStub; - private $scopes; - private $defaultCallSettings; - private $descriptors; - - /** - * Formats a string containing the fully-qualified path to represent - * a project resource. - * - * @param string $project - * - * @return string The formatted project resource. - * @experimental - */ - public static function formatProjectName($project) - { - return self::getProjectNameTemplate()->render([ - 'project' => $project, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a snapshot resource. - * - * @param string $project - * @param string $snapshot - * - * @return string The formatted snapshot resource. - * @experimental - */ - public static function formatSnapshotName($project, $snapshot) - { - return self::getSnapshotNameTemplate()->render([ - 'project' => $project, - 'snapshot' => $snapshot, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a subscription resource. - * - * @param string $project - * @param string $subscription - * - * @return string The formatted subscription resource. - * @experimental - */ - public static function formatSubscriptionName($project, $subscription) - { - return self::getSubscriptionNameTemplate()->render([ - 'project' => $project, - 'subscription' => $subscription, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a topic resource. - * - * @param string $project - * @param string $topic - * - * @return string The formatted topic resource. - * @experimental - */ - public static function formatTopicName($project, $topic) - { - return self::getTopicNameTemplate()->render([ - 'project' => $project, - 'topic' => $topic, - ]); - } - - /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - * - * @param string $projectName The fully-qualified project resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromProjectName($projectName) - { - return self::getProjectNameTemplate()->match($projectName)['project']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a snapshot resource. - * - * @param string $snapshotName The fully-qualified snapshot resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromSnapshotName($snapshotName) - { - return self::getSnapshotNameTemplate()->match($snapshotName)['project']; - } - - /** - * Parses the snapshot from the given fully-qualified path which - * represents a snapshot resource. - * - * @param string $snapshotName The fully-qualified snapshot resource. - * - * @return string The extracted snapshot value. - * @experimental - */ - public static function parseSnapshotFromSnapshotName($snapshotName) - { - return self::getSnapshotNameTemplate()->match($snapshotName)['snapshot']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a subscription resource. - * - * @param string $subscriptionName The fully-qualified subscription resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromSubscriptionName($subscriptionName) - { - return self::getSubscriptionNameTemplate()->match($subscriptionName)['project']; - } - - /** - * Parses the subscription from the given fully-qualified path which - * represents a subscription resource. - * - * @param string $subscriptionName The fully-qualified subscription resource. - * - * @return string The extracted subscription value. - * @experimental - */ - public static function parseSubscriptionFromSubscriptionName($subscriptionName) - { - return self::getSubscriptionNameTemplate()->match($subscriptionName)['subscription']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a topic resource. - * - * @param string $topicName The fully-qualified topic resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromTopicName($topicName) - { - return self::getTopicNameTemplate()->match($topicName)['project']; - } - - /** - * Parses the topic from the given fully-qualified path which - * represents a topic resource. - * - * @param string $topicName The fully-qualified topic resource. - * - * @return string The extracted topic value. - * @experimental - */ - public static function parseTopicFromTopicName($topicName) - { - return self::getTopicNameTemplate()->match($topicName)['topic']; - } - - private static function getProjectNameTemplate() - { - if (self::$projectNameTemplate == null) { - self::$projectNameTemplate = new PathTemplate('projects/{project}'); - } - - return self::$projectNameTemplate; - } - - private static function getSnapshotNameTemplate() - { - if (self::$snapshotNameTemplate == null) { - self::$snapshotNameTemplate = new PathTemplate('projects/{project}/snapshots/{snapshot}'); - } - - return self::$snapshotNameTemplate; - } - - private static function getSubscriptionNameTemplate() - { - if (self::$subscriptionNameTemplate == null) { - self::$subscriptionNameTemplate = new PathTemplate('projects/{project}/subscriptions/{subscription}'); - } - - return self::$subscriptionNameTemplate; - } - - private static function getTopicNameTemplate() - { - if (self::$topicNameTemplate == null) { - self::$topicNameTemplate = new PathTemplate('projects/{project}/topics/{topic}'); - } - - return self::$topicNameTemplate; - } - - private static function getPageStreamingDescriptors() - { - $listSubscriptionsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getSubscriptions', - ]); - $listSnapshotsPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getSnapshots', - ]); - - $pageStreamingDescriptors = [ - 'listSubscriptions' => $listSubscriptionsPageStreamingDescriptor, - 'listSnapshots' => $listSnapshotsPageStreamingDescriptor, - ]; - - return $pageStreamingDescriptors; - } - - private static function getGrpcStreamingDescriptors() - { - return [ - 'streamingPull' => [ - 'grpcStreamingType' => 'BidiStreaming', - 'resourcesGetMethod' => 'getReceivedMessages', - ], - ]; - } - - private static function getGapicVersion() - { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; - } - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'pubsub.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Google Cloud Pub/Sub API. - * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/pubsub', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'createSubscription' => $defaultDescriptors, - 'getSubscription' => $defaultDescriptors, - 'updateSubscription' => $defaultDescriptors, - 'listSubscriptions' => $defaultDescriptors, - 'deleteSubscription' => $defaultDescriptors, - 'modifyAckDeadline' => $defaultDescriptors, - 'acknowledge' => $defaultDescriptors, - 'pull' => $defaultDescriptors, - 'streamingPull' => $defaultDescriptors, - 'modifyPushConfig' => $defaultDescriptors, - 'listSnapshots' => $defaultDescriptors, - 'createSnapshot' => $defaultDescriptors, - 'deleteSnapshot' => $defaultDescriptors, - 'seek' => $defaultDescriptors, - 'setIamPolicy' => $defaultDescriptors, - 'getIamPolicy' => $defaultDescriptors, - 'testIamPermissions' => $defaultDescriptors, - ]; - $pageStreamingDescriptors = self::getPageStreamingDescriptors(); - foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { - $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; - } - $grpcStreamingDescriptors = self::getGrpcStreamingDescriptors(); - foreach ($grpcStreamingDescriptors as $method => $grpcStreamingDescriptor) { - $this->descriptors[$method]['grpcStreamingDescriptor'] = $grpcStreamingDescriptor; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/subscriber_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.pubsub.v1.Subscriber', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createIamPolicyStubFunction = function ($hostname, $opts) { - return new IAMPolicyGrpcClient($hostname, $opts); - }; - if (array_key_exists('createIamPolicyStubFunction', $options)) { - $createIamPolicyStubFunction = $options['createIamPolicyStubFunction']; - } - $this->iamPolicyStub = $this->grpcCredentialsHelper->createStub( - $createIamPolicyStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - $createSubscriberStubFunction = function ($hostname, $opts) { - return new SubscriberGrpcClient($hostname, $opts); - }; - if (array_key_exists('createSubscriberStubFunction', $options)) { - $createSubscriberStubFunction = $options['createSubscriberStubFunction']; - } - $this->subscriberStub = $this->grpcCredentialsHelper->createStub( - $createSubscriberStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Creates a subscription to a given topic. - * If the subscription already exists, returns `ALREADY_EXISTS`. - * If the corresponding topic doesn't exist, returns `NOT_FOUND`. - * - * If the name is not provided in the request, the server will assign a random - * name for this subscription on the same project as the topic, conforming - * to the - * [resource name format](https://cloud.google.com/pubsub/docs/overview#names). - * The generated name is populated in the returned Subscription object. - * Note that for REST API requests, you must specify a name in the request. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedName = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $formattedTopic = SubscriberClient::formatTopicName("[PROJECT]", "[TOPIC]"); - * $response = $subscriberClient->createSubscription($formattedName, $formattedTopic); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $name The name of the subscription. It must have the format - * `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must - * start with a letter, and contain only letters (`[A-Za-z]`), numbers - * (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), - * plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters - * in length, and it must not start with `"goog"`. - * @param string $topic The name of the topic from which this subscription is receiving messages. - * Format is `projects/{project}/topics/{topic}`. - * The value of this field will be `_deleted-topic_` if the topic has been - * deleted. - * @param array $optionalArgs { - * Optional. - * - * @type PushConfig $pushConfig - * If push delivery is used with this subscription, this field is - * used to configure it. An empty `pushConfig` signifies that the subscriber - * will pull and ack messages using API methods. - * @type int $ackDeadlineSeconds - * This value is the maximum time after a subscriber receives a message - * before the subscriber should acknowledge the message. After message - * delivery but before the ack deadline expires and before the message is - * acknowledged, it is an outstanding message and will not be delivered - * again during that time (on a best-effort basis). - * - * For pull subscriptions, this value is used as the initial value for the ack - * deadline. To override this value for a given message, call - * `ModifyAckDeadline` with the corresponding `ack_id` if using - * pull. - * The minimum custom deadline you can specify is 10 seconds. - * The maximum custom deadline you can specify is 600 seconds (10 minutes). - * If this parameter is 0, a default value of 10 seconds is used. - * - * For push delivery, this value is also used to set the request timeout for - * the call to the push endpoint. - * - * If the subscriber never acknowledges the message, the Pub/Sub - * system will eventually redeliver the message. - * @type bool $retainAckedMessages - * Indicates whether to retain acknowledged messages. If true, then - * messages are not expunged from the subscription's backlog, even if they are - * acknowledged, until they fall out of the `message_retention_duration` - * window. - * @type Duration $messageRetentionDuration - * How long to retain unacknowledged messages in the subscription's backlog, - * from the moment a message is published. - * If `retain_acked_messages` is true, then this also configures the retention - * of acknowledged messages, and thus configures how far back in time a `Seek` - * can be done. Defaults to 7 days. Cannot be more than 7 days or less than 10 - * minutes. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Pubsub\V1\Subscription - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createSubscription($name, $topic, $optionalArgs = []) - { - $request = new Subscription(); - $request->setName($name); - $request->setTopic($topic); - if (isset($optionalArgs['pushConfig'])) { - $request->setPushConfig($optionalArgs['pushConfig']); - } - if (isset($optionalArgs['ackDeadlineSeconds'])) { - $request->setAckDeadlineSeconds($optionalArgs['ackDeadlineSeconds']); - } - if (isset($optionalArgs['retainAckedMessages'])) { - $request->setRetainAckedMessages($optionalArgs['retainAckedMessages']); - } - if (isset($optionalArgs['messageRetentionDuration'])) { - $request->setMessageRetentionDuration($optionalArgs['messageRetentionDuration']); - } - - $mergedSettings = $this->defaultCallSettings['createSubscription']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'CreateSubscription', - $mergedSettings, - $this->descriptors['createSubscription'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets the configuration details of a subscription. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $response = $subscriberClient->getSubscription($formattedSubscription); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $subscription The name of the subscription to get. - * Format is `projects/{project}/subscriptions/{sub}`. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Pubsub\V1\Subscription - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getSubscription($subscription, $optionalArgs = []) - { - $request = new GetSubscriptionRequest(); - $request->setSubscription($subscription); - - $mergedSettings = $this->defaultCallSettings['getSubscription']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'GetSubscription', - $mergedSettings, - $this->descriptors['getSubscription'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Updates an existing subscription. Note that certain properties of a - * subscription, such as its topic, are not modifiable. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $subscription = new Subscription(); - * $updateMask = new FieldMask(); - * $response = $subscriberClient->updateSubscription($subscription, $updateMask); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param Subscription $subscription The updated subscription object. - * @param FieldMask $updateMask Indicates which fields in the provided subscription to update. - * Must be specified and non-empty. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Pubsub\V1\Subscription - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function updateSubscription($subscription, $updateMask, $optionalArgs = []) - { - $request = new UpdateSubscriptionRequest(); - $request->setSubscription($subscription); - $request->setUpdateMask($updateMask); - - $mergedSettings = $this->defaultCallSettings['updateSubscription']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'UpdateSubscription', - $mergedSettings, - $this->descriptors['updateSubscription'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists matching subscriptions. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedProject = SubscriberClient::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $subscriberClient->listSubscriptions($formattedProject); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $subscriberClient->listSubscriptions($formattedProject, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $project The name of the cloud project that subscriptions belong to. - * Format is `projects/{project}`. - * @param array $optionalArgs { - * Optional. - * - * @type int $pageSize - * The maximum number of resources contained in the underlying API - * response. The API may return fewer values in a page, even if - * there are additional values to be retrieved. - * @type string $pageToken - * A page token is used to specify a page of values to be returned. - * If no page token is specified (the default), the first page - * of values will be returned. Any page token used here must have - * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listSubscriptions($project, $optionalArgs = []) - { - $request = new ListSubscriptionsRequest(); - $request->setProject($project); - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listSubscriptions']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'ListSubscriptions', - $mergedSettings, - $this->descriptors['listSubscriptions'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Deletes an existing subscription. All messages retained in the subscription - * are immediately dropped. Calls to `Pull` after deletion will return - * `NOT_FOUND`. After a subscription is deleted, a new one may be created with - * the same name, but the new one has no association with the old - * subscription or its topic unless the same topic is specified. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $subscriberClient->deleteSubscription($formattedSubscription); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $subscription The subscription to delete. - * Format is `projects/{project}/subscriptions/{sub}`. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function deleteSubscription($subscription, $optionalArgs = []) - { - $request = new DeleteSubscriptionRequest(); - $request->setSubscription($subscription); - - $mergedSettings = $this->defaultCallSettings['deleteSubscription']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'DeleteSubscription', - $mergedSettings, - $this->descriptors['deleteSubscription'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Modifies the ack deadline for a specific message. This method is useful - * to indicate that more time is needed to process a message by the - * subscriber, or to make the message available for redelivery if the - * processing was interrupted. Note that this does not modify the - * subscription-level `ackDeadlineSeconds` used for subsequent messages. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $ackIds = []; - * $ackDeadlineSeconds = 0; - * $subscriberClient->modifyAckDeadline($formattedSubscription, $ackIds, $ackDeadlineSeconds); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $subscription The name of the subscription. - * Format is `projects/{project}/subscriptions/{sub}`. - * @param string[] $ackIds List of acknowledgment IDs. - * @param int $ackDeadlineSeconds The new ack deadline with respect to the time this request was sent to - * the Pub/Sub system. For example, if the value is 10, the new - * ack deadline will expire 10 seconds after the `ModifyAckDeadline` call - * was made. Specifying zero may immediately make the message available for - * another pull request. - * The minimum deadline you can specify is 0 seconds. - * The maximum deadline you can specify is 600 seconds (10 minutes). - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function modifyAckDeadline($subscription, $ackIds, $ackDeadlineSeconds, $optionalArgs = []) - { - $request = new ModifyAckDeadlineRequest(); - $request->setSubscription($subscription); - $request->setAckIds($ackIds); - $request->setAckDeadlineSeconds($ackDeadlineSeconds); - - $mergedSettings = $this->defaultCallSettings['modifyAckDeadline']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'ModifyAckDeadline', - $mergedSettings, - $this->descriptors['modifyAckDeadline'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Acknowledges the messages associated with the `ack_ids` in the - * `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages - * from the subscription. - * - * Acknowledging a message whose ack deadline has expired may succeed, - * but such a message may be redelivered later. Acknowledging a message more - * than once will not result in an error. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $ackIds = []; - * $subscriberClient->acknowledge($formattedSubscription, $ackIds); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $subscription The subscription whose message is being acknowledged. - * Format is `projects/{project}/subscriptions/{sub}`. - * @param string[] $ackIds The acknowledgment ID for the messages being acknowledged that was returned - * by the Pub/Sub system in the `Pull` response. Must not be empty. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function acknowledge($subscription, $ackIds, $optionalArgs = []) - { - $request = new AcknowledgeRequest(); - $request->setSubscription($subscription); - $request->setAckIds($ackIds); - - $mergedSettings = $this->defaultCallSettings['acknowledge']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'Acknowledge', - $mergedSettings, - $this->descriptors['acknowledge'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Pulls messages from the server. Returns an empty list if there are no - * messages available in the backlog. The server may return `UNAVAILABLE` if - * there are too many concurrent pull requests pending for the given - * subscription. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $maxMessages = 0; - * $response = $subscriberClient->pull($formattedSubscription, $maxMessages); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $subscription The subscription from which messages should be pulled. - * Format is `projects/{project}/subscriptions/{sub}`. - * @param int $maxMessages The maximum number of messages returned for this request. The Pub/Sub - * system may return fewer than the number specified. - * @param array $optionalArgs { - * Optional. - * - * @type bool $returnImmediately - * If this field set to true, the system will respond immediately even if - * it there are no messages available to return in the `Pull` response. - * Otherwise, the system may wait (for a bounded amount of time) until at - * least one message is available, rather than returning no messages. The - * client may cancel the request if it does not wish to wait any longer for - * the response. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Pubsub\V1\PullResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function pull($subscription, $maxMessages, $optionalArgs = []) - { - $request = new PullRequest(); - $request->setSubscription($subscription); - $request->setMaxMessages($maxMessages); - if (isset($optionalArgs['returnImmediately'])) { - $request->setReturnImmediately($optionalArgs['returnImmediately']); - } - - $mergedSettings = $this->defaultCallSettings['pull']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'Pull', - $mergedSettings, - $this->descriptors['pull'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * (EXPERIMENTAL) StreamingPull is an experimental feature. This RPC will - * respond with UNIMPLEMENTED errors unless you have been invited to test - * this feature. Contact cloud-pubsub@google.com with any questions. - * - * Establishes a stream with the server, which sends messages down to the - * client. The client streams acknowledgements and ack deadline modifications - * back to the server. The server will close the stream and return the status - * on any error. The server may close the stream with status `OK` to reassign - * server-side resources, in which case, the client should re-establish the - * stream. `UNAVAILABLE` may also be returned in the case of a transient error - * (e.g., a server restart). These should also be retried by the client. Flow - * control can be achieved by configuring the underlying RPC channel. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $streamAckDeadlineSeconds = 0; - * $request = new StreamingPullRequest(); - * $request->setSubscription($formattedSubscription); - * $request->setStreamAckDeadlineSeconds($streamAckDeadlineSeconds); - * $requests = [$request]; - * - * // Write all requests to the server, then read all responses until the - * // stream is complete - * $stream = $subscriberClient->streamingPull(); - * $stream->writeAll($requests); - * foreach ($stream->closeWriteAndReadAll() as $element) { - * // doSomethingWith($element); - * } - * - * // OR write requests individually, making read() calls if - * // required. Call closeWrite() once writes are complete, and read the - * // remaining responses from the server. - * $stream = $subscriberClient->streamingPull(); - * foreach ($requests as $request) { - * $stream->write($request); - * // if required, read a single response from the stream - * $element = $stream->read(); - * // doSomethingWith($element) - * } - * $stream->closeWrite(); - * $element = $stream->read(); - * while (!is_null($element)) { - * // doSomethingWith($element) - * $element = $stream->read(); - * } - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param array $optionalArgs { - * Optional. - * - * @type int $timeoutMillis - * Timeout to use for this call. - * } - * - * @return \Google\GAX\BidiStream - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function streamingPull($optionalArgs = []) - { - $mergedSettings = $this->defaultCallSettings['streamingPull']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'StreamingPull', - $mergedSettings, - $this->descriptors['streamingPull'] - ); - - return $callable( - null, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Modifies the `PushConfig` for a specified subscription. - * - * This may be used to change a push subscription to a pull one (signified by - * an empty `PushConfig`) or vice versa, or change the endpoint URL and other - * attributes of a push subscription. Messages will accumulate for delivery - * continuously through the call regardless of changes to the `PushConfig`. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $pushConfig = new PushConfig(); - * $subscriberClient->modifyPushConfig($formattedSubscription, $pushConfig); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $subscription The name of the subscription. - * Format is `projects/{project}/subscriptions/{sub}`. - * @param PushConfig $pushConfig The push configuration for future deliveries. - * - * An empty `pushConfig` indicates that the Pub/Sub system should - * stop pushing messages from the given subscription and allow - * messages to be pulled and acknowledged - effectively pausing - * the subscription if `Pull` is not called. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function modifyPushConfig($subscription, $pushConfig, $optionalArgs = []) - { - $request = new ModifyPushConfigRequest(); - $request->setSubscription($subscription); - $request->setPushConfig($pushConfig); - - $mergedSettings = $this->defaultCallSettings['modifyPushConfig']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'ModifyPushConfig', - $mergedSettings, - $this->descriptors['modifyPushConfig'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Lists the existing snapshots. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedProject = SubscriberClient::formatProjectName("[PROJECT]"); - * // Iterate through all elements - * $pagedResponse = $subscriberClient->listSnapshots($formattedProject); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $subscriberClient->listSnapshots($formattedProject, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $project The name of the cloud project that snapshots belong to. - * Format is `projects/{project}`. - * @param array $optionalArgs { - * Optional. - * - * @type int $pageSize - * The maximum number of resources contained in the underlying API - * response. The API may return fewer values in a page, even if - * there are additional values to be retrieved. - * @type string $pageToken - * A page token is used to specify a page of values to be returned. - * If no page token is specified (the default), the first page - * of values will be returned. Any page token used here must have - * been generated by a previous call to the API. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\GAX\PagedListResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function listSnapshots($project, $optionalArgs = []) - { - $request = new ListSnapshotsRequest(); - $request->setProject($project); - if (isset($optionalArgs['pageSize'])) { - $request->setPageSize($optionalArgs['pageSize']); - } - if (isset($optionalArgs['pageToken'])) { - $request->setPageToken($optionalArgs['pageToken']); - } - - $mergedSettings = $this->defaultCallSettings['listSnapshots']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'ListSnapshots', - $mergedSettings, - $this->descriptors['listSnapshots'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Creates a snapshot from the requested subscription. - * If the snapshot already exists, returns `ALREADY_EXISTS`. - * If the requested subscription doesn't exist, returns `NOT_FOUND`. - * - * If the name is not provided in the request, the server will assign a random - * name for this snapshot on the same project as the subscription, conforming - * to the - * [resource name format](https://cloud.google.com/pubsub/docs/overview#names). - * The generated name is populated in the returned Snapshot object. - * Note that for REST API requests, you must specify a name in the request. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedName = SubscriberClient::formatSnapshotName("[PROJECT]", "[SNAPSHOT]"); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $response = $subscriberClient->createSnapshot($formattedName, $formattedSubscription); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $name Optional user-provided name for this snapshot. - * If the name is not provided in the request, the server will assign a random - * name for this snapshot on the same project as the subscription. - * Note that for REST API requests, you must specify a name. - * Format is `projects/{project}/snapshots/{snap}`. - * @param string $subscription The subscription whose backlog the snapshot retains. - * Specifically, the created snapshot is guaranteed to retain: - * (a) The existing backlog on the subscription. More precisely, this is - * defined as the messages in the subscription's backlog that are - * unacknowledged upon the successful completion of the - * `CreateSnapshot` request; as well as: - * (b) Any messages published to the subscription's topic following the - * successful completion of the CreateSnapshot request. - * Format is `projects/{project}/subscriptions/{sub}`. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Pubsub\V1\Snapshot - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function createSnapshot($name, $subscription, $optionalArgs = []) - { - $request = new CreateSnapshotRequest(); - $request->setName($name); - $request->setSubscription($subscription); - - $mergedSettings = $this->defaultCallSettings['createSnapshot']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'CreateSnapshot', - $mergedSettings, - $this->descriptors['createSnapshot'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Removes an existing snapshot. All messages retained in the snapshot - * are immediately dropped. After a snapshot is deleted, a new one may be - * created with the same name, but the new one has no association with the old - * snapshot or its subscription, unless the same subscription is specified. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedSnapshot = SubscriberClient::formatSnapshotName("[PROJECT]", "[SNAPSHOT]"); - * $subscriberClient->deleteSnapshot($formattedSnapshot); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $snapshot The name of the snapshot to delete. - * Format is `projects/{project}/snapshots/{snap}`. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function deleteSnapshot($snapshot, $optionalArgs = []) - { - $request = new DeleteSnapshotRequest(); - $request->setSnapshot($snapshot); - - $mergedSettings = $this->defaultCallSettings['deleteSnapshot']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'DeleteSnapshot', - $mergedSettings, - $this->descriptors['deleteSnapshot'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Seeks an existing subscription to a point in time or to a given snapshot, - * whichever is provided in the request. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedSubscription = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $response = $subscriberClient->seek($formattedSubscription); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $subscription The subscription to affect. - * @param array $optionalArgs { - * Optional. - * - * @type Timestamp $time - * The time to seek to. - * Messages retained in the subscription that were published before this - * time are marked as acknowledged, and messages retained in the - * subscription that were published after this time are marked as - * unacknowledged. Note that this operation affects only those messages - * retained in the subscription (configured by the combination of - * `message_retention_duration` and `retain_acked_messages`). For example, - * if `time` corresponds to a point before the message retention - * window (or to a point before the system's notion of the subscription - * creation time), only retained messages will be marked as unacknowledged, - * and already-expunged messages will not be restored. - * @type string $snapshot - * The snapshot to seek to. The snapshot's topic must be the same as that of - * the provided subscription. - * Format is `projects/{project}/snapshots/{snap}`. - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Pubsub\V1\SeekResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function seek($subscription, $optionalArgs = []) - { - $request = new SeekRequest(); - $request->setSubscription($subscription); - if (isset($optionalArgs['time'])) { - $request->setTime($optionalArgs['time']); - } - if (isset($optionalArgs['snapshot'])) { - $request->setSnapshot($optionalArgs['snapshot']); - } - - $mergedSettings = $this->defaultCallSettings['seek']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->subscriberStub, - 'Seek', - $mergedSettings, - $this->descriptors['seek'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Sets the access control policy on the specified resource. Replaces any - * existing policy. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedResource = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $policy = new Policy(); - * $response = $subscriberClient->setIamPolicy($formattedResource, $policy); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $resource REQUIRED: The resource for which the policy is being specified. - * `resource` is usually specified as a path. For example, a Project - * resource is specified as `projects/{project}`. - * @param Policy $policy REQUIRED: The complete policy to be applied to the `resource`. The size of - * the policy is limited to a few 10s of KB. An empty policy is a - * valid policy but certain Cloud Platform services (such as Projects) - * might reject them. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Iam\V1\Policy - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function setIamPolicy($resource, $policy, $optionalArgs = []) - { - $request = new SetIamPolicyRequest(); - $request->setResource($resource); - $request->setPolicy($policy); - - $mergedSettings = $this->defaultCallSettings['setIamPolicy']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->iamPolicyStub, - 'SetIamPolicy', - $mergedSettings, - $this->descriptors['setIamPolicy'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Gets the access control policy for a resource. - * Returns an empty policy if the resource exists and does not have a policy - * set. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedResource = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $response = $subscriberClient->getIamPolicy($formattedResource); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $resource REQUIRED: The resource for which the policy is being requested. - * `resource` is usually specified as a path. For example, a Project - * resource is specified as `projects/{project}`. - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Iam\V1\Policy - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function getIamPolicy($resource, $optionalArgs = []) - { - $request = new GetIamPolicyRequest(); - $request->setResource($resource); - - $mergedSettings = $this->defaultCallSettings['getIamPolicy']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->iamPolicyStub, - 'GetIamPolicy', - $mergedSettings, - $this->descriptors['getIamPolicy'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Returns permissions that a caller has on the specified resource. - * If the resource does not exist, this will return an empty set of - * permissions, not a NOT_FOUND error. - * - * Sample code: - * ``` - * try { - * $subscriberClient = new SubscriberClient(); - * $formattedResource = SubscriberClient::formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); - * $permissions = []; - * $response = $subscriberClient->testIamPermissions($formattedResource, $permissions); - * } finally { - * $subscriberClient->close(); - * } - * ``` - * - * @param string $resource REQUIRED: The resource for which the policy detail is being requested. - * `resource` is usually specified as a path. For example, a Project - * resource is specified as `projects/{project}`. - * @param string[] $permissions The set of permissions to check for the `resource`. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. For more - * information see - * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). - * @param array $optionalArgs { - * Optional. - * - * @type \Google\GAX\RetrySettings $retrySettings - * Retry settings to use for this call. If present, then - * $timeoutMillis is ignored. - * @type int $timeoutMillis - * Timeout to use for this call. Only used if $retrySettings - * is not set. - * } - * - * @return \Google\Iam\V1\TestIamPermissionsResponse - * - * @throws \Google\GAX\ApiException if the remote call fails - * @experimental - */ - public function testIamPermissions($resource, $permissions, $optionalArgs = []) - { - $request = new TestIamPermissionsRequest(); - $request->setResource($resource); - $request->setPermissions($permissions); - - $mergedSettings = $this->defaultCallSettings['testIamPermissions']->merge( - new CallSettings($optionalArgs) - ); - $callable = ApiCallable::createApiCall( - $this->iamPolicyStub, - 'TestIamPermissions', - $mergedSettings, - $this->descriptors['testIamPermissions'] - ); - - return $callable( - $request, - [], - ['call_credentials_callback' => $this->createCredentialsCallback()]); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new - * calls are immediately cancelled. - * - * @experimental - */ - public function close() - { - $this->iamPolicyStub->close(); - $this->subscriberStub->close(); - } - - private function createCredentialsCallback() - { - return $this->grpcCredentialsHelper->createCallCredentialsCallback(); - } + // This class is intentionally empty, and is intended to hold manual additions to the generated {@see SubscriberClientImpl} class. } diff --git a/src/PubSub/V1/resources/publisher_client_config.json b/src/PubSub/V1/resources/publisher_client_config.json index 905e790b2181..9fb679cbad27 100644 --- a/src/PubSub/V1/resources/publisher_client_config.json +++ b/src/PubSub/V1/resources/publisher_client_config.json @@ -33,7 +33,7 @@ "max_retry_delay_millis": 60000, "initial_rpc_timeout_millis": 12000, "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 12000, + "max_rpc_timeout_millis": 30000, "total_timeout_millis": 600000 } }, diff --git a/src/PubSub/V1/resources/subscriber_client_config.json b/src/PubSub/V1/resources/subscriber_client_config.json index e5ae4c0b2719..413a57aed9f2 100644 --- a/src/PubSub/V1/resources/subscriber_client_config.json +++ b/src/PubSub/V1/resources/subscriber_client_config.json @@ -33,6 +33,15 @@ "rpc_timeout_multiplier": 1.0, "max_rpc_timeout_millis": 12000, "total_timeout_millis": 600000 + }, + "streaming_messaging": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 600000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 600000, + "total_timeout_millis": 600000 } }, "methods": { diff --git a/src/Spanner/Admin/Database/V1/DatabaseAdminClient.php b/src/Spanner/Admin/Database/V1/DatabaseAdminClient.php index e01212747758..5b64c92de04b 100644 --- a/src/Spanner/Admin/Database/V1/DatabaseAdminClient.php +++ b/src/Spanner/Admin/Database/V1/DatabaseAdminClient.php @@ -30,1079 +30,12 @@ namespace Google\Cloud\Spanner\Admin\Database\V1; -use Google\GAX\AgentHeaderDescriptor; -use Google\GAX\ApiCallable; -use Google\GAX\CallSettings; -use Google\GAX\GrpcConstants; -use Google\GAX\GrpcCredentialsHelper; -use Google\GAX\LongRunning\OperationsClient; -use Google\GAX\OperationResponse; -use Google\GAX\PageStreamingDescriptor; -use Google\GAX\PathTemplate; -use Google\Iam\V1\GetIamPolicyRequest; -use Google\Iam\V1\Policy; -use Google\Iam\V1\SetIamPolicyRequest; -use Google\Iam\V1\TestIamPermissionsRequest; -use Google\Spanner\Admin\Database\V1\CreateDatabaseMetadata; -use Google\Spanner\Admin\Database\V1\CreateDatabaseRequest; -use Google\Spanner\Admin\Database\V1\Database; -use Google\Spanner\Admin\Database\V1\DatabaseAdminGrpcClient; -use Google\Spanner\Admin\Database\V1\DropDatabaseRequest; -use Google\Spanner\Admin\Database\V1\GetDatabaseDdlRequest; -use Google\Spanner\Admin\Database\V1\GetDatabaseRequest; -use Google\Spanner\Admin\Database\V1\ListDatabasesRequest; -use Google\Spanner\Admin\Database\V1\UpdateDatabaseDdlMetadata; -use Google\Spanner\Admin\Database\V1\UpdateDatabaseDdlRequest; +use Google\Cloud\Spanner\Admin\Database\V1\Gapic\DatabaseAdminGapicClient; /** - * Service Description: Cloud Spanner Database Admin API. - * - * The Cloud Spanner Database Admin API can be used to create, drop, and - * list databases. It also enables updating the schema of pre-existing - * databases. - * - * EXPERIMENTAL: this client library class has not yet been declared beta. This class may change - * more frequently than those which have been declared beta or 1.0, including changes which break - * backwards compatibility. - * - * This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - * ``` - * try { - * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedParent = DatabaseAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); - * // Iterate through all elements - * $pagedResponse = $databaseAdminClient->listDatabases($formattedParent); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $databaseAdminClient->listDatabases($formattedParent, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $databaseAdminClient->close(); - * } - * ``` - * - * Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. - * - * @experimental + * {@inheritdoc} */ -class DatabaseAdminClient +class DatabaseAdminClient extends DatabaseAdminGapicClient { - /** - * The default address of the service. - */ - const SERVICE_ADDRESS = 'spanner.googleapis.com'; - - /** - * The default port of the service. - */ - const DEFAULT_SERVICE_PORT = 443; - - /** - * The default timeout for non-retrying methods. - */ - const DEFAULT_TIMEOUT_MILLIS = 30000; - - /** - * The name of the code generator, to be included in the agent header. - */ - const CODEGEN_NAME = 'gapic'; - - /** - * The code generator version, to be included in the agent header. - */ - const CODEGEN_VERSION = '0.0.5'; - - private static $instanceNameTemplate; - private static $databaseNameTemplate; - - private $grpcCredentialsHelper; - private $databaseAdminStub; - private $scopes; - private $defaultCallSettings; - private $descriptors; - private $operationsClient; - - /** - * Formats a string containing the fully-qualified path to represent - * a instance resource. - * - * @param string $project - * @param string $instance - * - * @return string The formatted instance resource. - * @experimental - */ - public static function formatInstanceName($project, $instance) - { - return self::getInstanceNameTemplate()->render([ - 'project' => $project, - 'instance' => $instance, - ]); - } - - /** - * Formats a string containing the fully-qualified path to represent - * a database resource. - * - * @param string $project - * @param string $instance - * @param string $database - * - * @return string The formatted database resource. - * @experimental - */ - public static function formatDatabaseName($project, $instance, $database) - { - return self::getDatabaseNameTemplate()->render([ - 'project' => $project, - 'instance' => $instance, - 'database' => $database, - ]); - } - - /** - * Parses the project from the given fully-qualified path which - * represents a instance resource. - * - * @param string $instanceName The fully-qualified instance resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromInstanceName($instanceName) - { - return self::getInstanceNameTemplate()->match($instanceName)['project']; - } - - /** - * Parses the instance from the given fully-qualified path which - * represents a instance resource. - * - * @param string $instanceName The fully-qualified instance resource. - * - * @return string The extracted instance value. - * @experimental - */ - public static function parseInstanceFromInstanceName($instanceName) - { - return self::getInstanceNameTemplate()->match($instanceName)['instance']; - } - - /** - * Parses the project from the given fully-qualified path which - * represents a database resource. - * - * @param string $databaseName The fully-qualified database resource. - * - * @return string The extracted project value. - * @experimental - */ - public static function parseProjectFromDatabaseName($databaseName) - { - return self::getDatabaseNameTemplate()->match($databaseName)['project']; - } - - /** - * Parses the instance from the given fully-qualified path which - * represents a database resource. - * - * @param string $databaseName The fully-qualified database resource. - * - * @return string The extracted instance value. - * @experimental - */ - public static function parseInstanceFromDatabaseName($databaseName) - { - return self::getDatabaseNameTemplate()->match($databaseName)['instance']; - } - - /** - * Parses the database from the given fully-qualified path which - * represents a database resource. - * - * @param string $databaseName The fully-qualified database resource. - * - * @return string The extracted database value. - * @experimental - */ - public static function parseDatabaseFromDatabaseName($databaseName) - { - return self::getDatabaseNameTemplate()->match($databaseName)['database']; - } - - private static function getInstanceNameTemplate() - { - if (self::$instanceNameTemplate == null) { - self::$instanceNameTemplate = new PathTemplate('projects/{project}/instances/{instance}'); - } - - return self::$instanceNameTemplate; - } - - private static function getDatabaseNameTemplate() - { - if (self::$databaseNameTemplate == null) { - self::$databaseNameTemplate = new PathTemplate('projects/{project}/instances/{instance}/databases/{database}'); - } - - return self::$databaseNameTemplate; - } - - private static function getPageStreamingDescriptors() - { - $listDatabasesPageStreamingDescriptor = - new PageStreamingDescriptor([ - 'requestPageTokenGetMethod' => 'getPageToken', - 'requestPageTokenSetMethod' => 'setPageToken', - 'requestPageSizeGetMethod' => 'getPageSize', - 'requestPageSizeSetMethod' => 'setPageSize', - 'responsePageTokenGetMethod' => 'getNextPageToken', - 'resourcesGetMethod' => 'getDatabases', - ]); - - $pageStreamingDescriptors = [ - 'listDatabases' => $listDatabasesPageStreamingDescriptor, - ]; - - return $pageStreamingDescriptors; - } - - private static function getLongRunningDescriptors() - { - return [ - 'createDatabase' => [ - 'operationReturnType' => '\Google\Spanner\Admin\Database\V1\Database', - 'metadataReturnType' => '\Google\Spanner\Admin\Database\V1\CreateDatabaseMetadata', - ], - 'updateDatabaseDdl' => [ - 'operationReturnType' => '\Google\Protobuf\GPBEmpty', - 'metadataReturnType' => '\Google\Spanner\Admin\Database\V1\UpdateDatabaseDdlMetadata', - ], - ]; - } - - private static function getGapicVersion() - { - if (file_exists(__DIR__.'/../VERSION')) { - return trim(file_get_contents(__DIR__.'/../VERSION')); - } elseif (class_exists('\Google\Cloud\ServiceBuilder')) { - return \Google\Cloud\ServiceBuilder::VERSION; - } else { - return; - } - } - - /** - * Return an OperationsClient object with the same endpoint as $this. - * - * @return \Google\GAX\LongRunning\OperationsClient - * @experimental - */ - public function getOperationsClient() - { - return $this->operationsClient; - } - - /** - * Resume an existing long running operation that was previously started - * by a long running API method. If $methodName is not provided, or does - * not match a long running API method, then the operation can still be - * resumed, but the OperationResponse object will not deserialize the - * final response. - * - * @param string $operationName The name of the long running operation - * @param string $methodName The name of the method used to start the operation - * - * @return \Google\GAX\OperationResponse - * @experimental - */ - public function resumeOperation($operationName, $methodName = null) - { - $lroDescriptors = self::getLongRunningDescriptors(); - if (!is_null($methodName) && array_key_exists($methodName, $lroDescriptors)) { - $options = $lroDescriptors[$methodName]; - } else { - $options = []; - } - $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); - $operation->reload(); - - return $operation; - } - - // TODO(garrettjones): add channel (when supported in gRPC) - /** - * Constructor. - * - * @param array $options { - * Optional. Options for configuring the service API wrapper. - * - * @type string $serviceAddress The domain name of the API remote host. - * Default 'spanner.googleapis.com'. - * @type mixed $port The port on which to connect to the remote host. Default 443. - * @type \Grpc\ChannelCredentials $sslCreds - * A `ChannelCredentials` for use with an SSL-enabled channel. - * Default: a credentials object returned from - * \Grpc\ChannelCredentials::createSsl() - * @type array $scopes A string array of scopes to use when acquiring credentials. - * Default the scopes for the Cloud Spanner Database Admin API. - * @type array $retryingOverride - * An associative array of string => RetryOptions, where the keys - * are method names (e.g. 'createFoo'), that overrides default retrying - * settings. A value of null indicates that the method in question should - * not retry. - * @type int $timeoutMillis The timeout in milliseconds to use for calls - * that don't use retries. For calls that use retries, - * set the timeout in RetryOptions. - * Default: 30000 (30 seconds) - * @type \Google\Auth\CredentialsLoader $credentialsLoader - * A CredentialsLoader object created using the - * Google\Auth library. - * } - * @experimental - */ - public function __construct($options = []) - { - $defaultOptions = [ - 'serviceAddress' => self::SERVICE_ADDRESS, - 'port' => self::DEFAULT_SERVICE_PORT, - 'scopes' => [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/spanner.admin', - ], - 'retryingOverride' => null, - 'timeoutMillis' => self::DEFAULT_TIMEOUT_MILLIS, - 'libName' => null, - 'libVersion' => null, - ]; - $options = array_merge($defaultOptions, $options); - - if (array_key_exists('operationsClient', $options)) { - $this->operationsClient = $options['operationsClient']; - } else { - $operationsClientOptions = $options; - unset($operationsClientOptions['timeoutMillis']); - unset($operationsClientOptions['retryingOverride']); - $this->operationsClient = new OperationsClient($operationsClientOptions); - } - - $gapicVersion = $options['libVersion'] ?: self::getGapicVersion(); - - $headerDescriptor = new AgentHeaderDescriptor([ - 'libName' => $options['libName'], - 'libVersion' => $options['libVersion'], - 'gapicVersion' => $gapicVersion, - ]); - - $defaultDescriptors = ['headerDescriptor' => $headerDescriptor]; - $this->descriptors = [ - 'listDatabases' => $defaultDescriptors, - 'createDatabase' => $defaultDescriptors, - 'getDatabase' => $defaultDescriptors, - 'updateDatabaseDdl' => $defaultDescriptors, - 'dropDatabase' => $defaultDescriptors, - 'getDatabaseDdl' => $defaultDescriptors, - 'setIamPolicy' => $defaultDescriptors, - 'getIamPolicy' => $defaultDescriptors, - 'testIamPermissions' => $defaultDescriptors, - ]; - $pageStreamingDescriptors = self::getPageStreamingDescriptors(); - foreach ($pageStreamingDescriptors as $method => $pageStreamingDescriptor) { - $this->descriptors[$method]['pageStreamingDescriptor'] = $pageStreamingDescriptor; - } - $longRunningDescriptors = self::getLongRunningDescriptors(); - foreach ($longRunningDescriptors as $method => $longRunningDescriptor) { - $this->descriptors[$method]['longRunningDescriptor'] = $longRunningDescriptor + ['operationsClient' => $this->operationsClient]; - } - - $clientConfigJsonString = file_get_contents(__DIR__.'/resources/database_admin_client_config.json'); - $clientConfig = json_decode($clientConfigJsonString, true); - $this->defaultCallSettings = - CallSettings::load( - 'google.spanner.admin.database.v1.DatabaseAdmin', - $clientConfig, - $options['retryingOverride'], - GrpcConstants::getStatusCodeNames(), - $options['timeoutMillis'] - ); - - $this->scopes = $options['scopes']; - - $createStubOptions = []; - if (array_key_exists('sslCreds', $options)) { - $createStubOptions['sslCreds'] = $options['sslCreds']; - } - $grpcCredentialsHelperOptions = array_diff_key($options, $defaultOptions); - $this->grpcCredentialsHelper = new GrpcCredentialsHelper($this->scopes, $grpcCredentialsHelperOptions); - - $createDatabaseAdminStubFunction = function ($hostname, $opts) { - return new DatabaseAdminGrpcClient($hostname, $opts); - }; - if (array_key_exists('createDatabaseAdminStubFunction', $options)) { - $createDatabaseAdminStubFunction = $options['createDatabaseAdminStubFunction']; - } - $this->databaseAdminStub = $this->grpcCredentialsHelper->createStub( - $createDatabaseAdminStubFunction, - $options['serviceAddress'], - $options['port'], - $createStubOptions - ); - } - - /** - * Lists Cloud Spanner databases. - * - * Sample code: - * ``` - * try { - * $databaseAdminClient = new DatabaseAdminClient(); - * $formattedParent = DatabaseAdminClient::formatInstanceName("[PROJECT]", "[INSTANCE]"); - * // Iterate through all elements - * $pagedResponse = $databaseAdminClient->listDatabases($formattedParent); - * foreach ($pagedResponse->iterateAllElements() as $element) { - * // doSomethingWith($element); - * } - * - * // OR iterate over pages of elements, with the maximum page size set to 5 - * $pagedResponse = $databaseAdminClient->listDatabases($formattedParent, ['pageSize' => 5]); - * foreach ($pagedResponse->iteratePages() as $page) { - * foreach ($page as $element) { - * // doSomethingWith($element); - * } - * } - * } finally { - * $databaseAdminClient->close(); - * } - * ``` - * - * @param string $parent Required. The instance whose databases should be listed. - * Values are of the form `projects/