...

Source file src/github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/gcpchaos/utils/utils.go

Documentation: github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/gcpchaos/utils

     1  // Copyright 2021 Chaos Mesh Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  // http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  //
    15  
    16  package utils
    17  
    18  import (
    19  	"context"
    20  	"encoding/base64"
    21  
    22  	compute "google.golang.org/api/compute/v1"
    23  	"google.golang.org/api/option"
    24  	v1 "k8s.io/api/core/v1"
    25  	"k8s.io/apimachinery/pkg/types"
    26  	"sigs.k8s.io/controller-runtime/pkg/client"
    27  
    28  	"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
    29  )
    30  
    31  // GetComputeService is used to get the GCP compute Service.
    32  func GetComputeService(ctx context.Context, cli client.Client, gcpchaos *v1alpha1.GCPChaos) (*compute.Service, error) {
    33  	if gcpchaos.Spec.SecretName != nil {
    34  		secret := &v1.Secret{}
    35  		err := cli.Get(ctx, types.NamespacedName{
    36  			Name:      *gcpchaos.Spec.SecretName,
    37  			Namespace: gcpchaos.Namespace,
    38  		}, secret)
    39  		if err != nil {
    40  			return nil, err
    41  		}
    42  
    43  		decodeBytes, err := base64.StdEncoding.DecodeString(string(secret.Data["service_account"]))
    44  		if err != nil {
    45  			return nil, err
    46  		}
    47  		computeService, err := compute.NewService(ctx, option.WithCredentialsJSON(decodeBytes))
    48  		if err != nil {
    49  			return nil, err
    50  		}
    51  		return computeService, nil
    52  	}
    53  
    54  	computeService, err := compute.NewService(ctx)
    55  	if err != nil {
    56  		return nil, err
    57  	}
    58  	return computeService, nil
    59  }
    60