kubernetes_helpers.rb 29 KB
Newer Older
1 2
# frozen_string_literal: true

3 4 5
module KubernetesHelpers
  include Gitlab::Kubernetes

6 7 8 9 10 11 12 13
  def kube_response(body)
    { body: body.to_json }
  end

  def kube_pods_response
    kube_response(kube_pods_body)
  end

14 15 16 17
  def kube_pod_response
    kube_response(kube_pod)
  end

18
  def kube_logs_response
19
    { body: kube_logs_body }
20 21
  end

22 23 24 25
  def kube_deployments_response
    kube_response(kube_deployments_body)
  end

26
  def stub_kubeclient_discover_base(api_url)
27
    WebMock.stub_request(:get, api_url + '/api/v1').to_return(kube_response(kube_v1_discovery_body))
28 29 30 31 32 33 34 35
    WebMock
      .stub_request(:get, api_url + '/apis/extensions/v1beta1')
      .to_return(kube_response(kube_v1beta1_discovery_body))
    WebMock
      .stub_request(:get, api_url + '/apis/rbac.authorization.k8s.io/v1')
      .to_return(kube_response(kube_v1_rbac_authorization_discovery_body))
  end

36 37 38 39 40 41 42 43
  def stub_kubeclient_discover_istio(api_url)
    stub_kubeclient_discover_base(api_url)

    WebMock
      .stub_request(:get, api_url + '/apis/networking.istio.io/v1alpha3')
      .to_return(kube_response(kube_istio_discovery_body))
  end

44 45 46 47 48 49 50 51 52 53 54 55 56 57
  def stub_kubeclient_discover(api_url)
    stub_kubeclient_discover_base(api_url)

    WebMock
      .stub_request(:get, api_url + '/apis/serving.knative.dev/v1alpha1')
      .to_return(kube_response(kube_v1alpha1_serving_knative_discovery_body))
  end

  def stub_kubeclient_discover_knative_not_found(api_url)
    stub_kubeclient_discover_base(api_url)

    WebMock
      .stub_request(:get, api_url + '/apis/serving.knative.dev/v1alpha1')
      .to_return(status: [404, "Resource Not Found"])
58 59
  end

60
  def stub_kubeclient_service_pods(response = nil, options = {})
61
    stub_kubeclient_discover(service.api_url)
62 63 64 65

    namespace_path = options[:namespace].present? ? "namespaces/#{options[:namespace]}/" : ""

    pods_url = service.api_url + "/api/v1/#{namespace_path}pods"
66 67 68 69

    WebMock.stub_request(:get, pods_url).to_return(response || kube_pods_response)
  end

70
  def stub_kubeclient_pods(namespace, status: nil)
71
    stub_kubeclient_discover(service.api_url)
72 73
    pods_url = service.api_url + "/api/v1/namespaces/#{namespace}/pods"
    response = { status: status } if status
74 75 76 77

    WebMock.stub_request(:get, pods_url).to_return(response || kube_pods_response)
  end

78
  def stub_kubeclient_pod_details(pod, namespace, status: nil)
79
    stub_kubeclient_discover(service.api_url)
80 81

    pod_url = service.api_url + "/api/v1/namespaces/#{namespace}/pods/#{pod}"
82
    response = { status: status } if status
83

84 85 86 87 88 89 90 91 92 93 94
    WebMock.stub_request(:get, pod_url).to_return(response || kube_pod_response)
  end

  def stub_kubeclient_logs(pod_name, namespace, container: nil, status: nil, message: nil)
    stub_kubeclient_discover(service.api_url)

    if container
      container_query_param = "container=#{container}&"
    end

    logs_url = service.api_url + "/api/v1/namespaces/#{namespace}/pods/#{pod_name}" \
95
    "/log?#{container_query_param}tailLines=#{Clusters::Platforms::Kubernetes::LOGS_LIMIT}&timestamps=true"
96 97 98 99 100 101

    if status
      response = { status: status }
      response[:body] = { message: message }.to_json if message
    end

102 103 104
    WebMock.stub_request(:get, logs_url).to_return(response || kube_logs_response)
  end

105
  def stub_kubeclient_deployments(namespace, status: nil)
106
    stub_kubeclient_discover(service.api_url)
107 108
    deployments_url = service.api_url + "/apis/extensions/v1beta1/namespaces/#{namespace}/deployments"
    response = { status: status } if status
109 110 111 112

    WebMock.stub_request(:get, deployments_url).to_return(response || kube_deployments_response)
  end

113 114 115
  def stub_kubeclient_knative_services(options = {})
    namespace_path = options[:namespace].present? ? "namespaces/#{options[:namespace]}/" : ""

116 117
    options[:name] ||= "kubetest"
    options[:domain] ||= "example.com"
118
    options[:response] ||= kube_response(kube_knative_services_body(options))
119 120 121

    stub_kubeclient_discover(service.api_url)

122 123 124
    knative_url = service.api_url + "/apis/serving.knative.dev/v1alpha1/#{namespace_path}services"

    WebMock.stub_request(:get, knative_url).to_return(options[:response])
125 126
  end

127
  def stub_kubeclient_get_secret(api_url, **options)
128
    options[:metadata_name] ||= "default-token-1"
129
    options[:namespace] ||= "default"
130

131
    WebMock.stub_request(:get, api_url + "/api/v1/namespaces/#{options[:namespace]}/secrets/#{options[:metadata_name]}")
132
      .to_return(kube_response(kube_v1_secret_body(options)))
133 134
  end

135
  def stub_kubeclient_get_secret_error(api_url, name, namespace: 'default', status: 404)
136
    WebMock.stub_request(:get, api_url + "/api/v1/namespaces/#{namespace}/secrets/#{name}")
137
      .to_return(status: [status, "Internal Server Error"])
138 139
  end

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
  def stub_kubeclient_get_secret_not_found_then_found(api_url, **options)
    options[:metadata_name] ||= "default-token-1"
    options[:namespace] ||= "default"

    WebMock.stub_request(:get, api_url + "/api/v1/namespaces/#{options[:namespace]}/secrets/#{options[:metadata_name]}")
      .to_return(status: [404, "Not Found"])
      .then
      .to_return(kube_response(kube_v1_secret_body(options)))
  end

  def stub_kubeclient_get_secret_missing_token_then_with_token(api_url, **options)
    options[:metadata_name] ||= "default-token-1"
    options[:namespace] ||= "default"

    WebMock.stub_request(:get, api_url + "/api/v1/namespaces/#{options[:namespace]}/secrets/#{options[:metadata_name]}")
      .to_return(kube_response(kube_v1_secret_body(options.merge(token: nil))))
      .then
      .to_return(kube_response(kube_v1_secret_body(options)))
  end

160 161 162 163 164
  def stub_kubeclient_get_service_account(api_url, name, namespace: 'default')
    WebMock.stub_request(:get, api_url + "/api/v1/namespaces/#{namespace}/serviceaccounts/#{name}")
      .to_return(kube_response({}))
  end

165 166 167 168 169
  def stub_kubeclient_get_service_account_error(api_url, name, namespace: 'default', status: 404)
    WebMock.stub_request(:get, api_url + "/api/v1/namespaces/#{namespace}/serviceaccounts/#{name}")
      .to_return(status: [status, "Internal Server Error"])
  end

170 171 172 173 174
  def stub_kubeclient_create_service_account(api_url, namespace: 'default')
    WebMock.stub_request(:post, api_url + "/api/v1/namespaces/#{namespace}/serviceaccounts")
      .to_return(kube_response({}))
  end

175 176 177 178 179
  def stub_kubeclient_create_service_account_error(api_url, namespace: 'default')
    WebMock.stub_request(:post, api_url + "/api/v1/namespaces/#{namespace}/serviceaccounts")
      .to_return(status: [500, "Internal Server Error"])
  end

180 181 182 183 184
  def stub_kubeclient_put_service_account(api_url, name, namespace: 'default')
    WebMock.stub_request(:put, api_url + "/api/v1/namespaces/#{namespace}/serviceaccounts/#{name}")
      .to_return(kube_response({}))
  end

185 186 187 188 189
  def stub_kubeclient_create_secret(api_url, namespace: 'default')
    WebMock.stub_request(:post, api_url + "/api/v1/namespaces/#{namespace}/secrets")
      .to_return(kube_response({}))
  end

190 191 192 193 194 195 196 197 198 199
  def stub_kubeclient_put_secret(api_url, name, namespace: 'default')
    WebMock.stub_request(:put, api_url + "/api/v1/namespaces/#{namespace}/secrets/#{name}")
      .to_return(kube_response({}))
  end

  def stub_kubeclient_get_cluster_role_binding_error(api_url, name, status: 404)
    WebMock.stub_request(:get, api_url + "/apis/rbac.authorization.k8s.io/v1/clusterrolebindings/#{name}")
      .to_return(status: [status, "Internal Server Error"])
  end

200 201 202 203 204
  def stub_kubeclient_create_cluster_role_binding(api_url)
    WebMock.stub_request(:post, api_url + '/apis/rbac.authorization.k8s.io/v1/clusterrolebindings')
      .to_return(kube_response({}))
  end

205 206 207 208 209
  def stub_kubeclient_get_role_binding(api_url, name, namespace: 'default')
    WebMock.stub_request(:get, api_url + "/apis/rbac.authorization.k8s.io/v1/namespaces/#{namespace}/rolebindings/#{name}")
      .to_return(kube_response({}))
  end

210 211 212 213 214
  def stub_kubeclient_get_role_binding_error(api_url, name, namespace: 'default', status: 404)
    WebMock.stub_request(:get, api_url + "/apis/rbac.authorization.k8s.io/v1/namespaces/#{namespace}/rolebindings/#{name}")
      .to_return(status: [status, "Internal Server Error"])
  end

215 216 217 218 219
  def stub_kubeclient_create_role_binding(api_url, namespace: 'default')
    WebMock.stub_request(:post, api_url + "/apis/rbac.authorization.k8s.io/v1/namespaces/#{namespace}/rolebindings")
      .to_return(kube_response({}))
  end

220 221 222 223 224
  def stub_kubeclient_put_role_binding(api_url, name, namespace: 'default')
    WebMock.stub_request(:put, api_url + "/apis/rbac.authorization.k8s.io/v1/namespaces/#{namespace}/rolebindings/#{name}")
      .to_return(kube_response({}))
  end

225 226 227 228 229
  def stub_kubeclient_create_namespace(api_url)
    WebMock.stub_request(:post, api_url + "/api/v1/namespaces")
      .to_return(kube_response({}))
  end

230
  def stub_kubeclient_get_namespace(api_url, namespace: 'default')
231
    WebMock.stub_request(:get, api_url + "/api/v1/namespaces/#{namespace}")
232 233 234
      .to_return(kube_response({}))
  end

235 236 237 238 239
  def stub_kubeclient_put_role(api_url, name, namespace: 'default')
    WebMock.stub_request(:put, api_url + "/apis/rbac.authorization.k8s.io/v1/namespaces/#{namespace}/roles/#{name}")
      .to_return(kube_response({}))
  end

240 241 242 243 244 245 246 247 248 249
  def stub_kubeclient_get_gateway(api_url, name, namespace: 'default')
    WebMock.stub_request(:get, api_url + "/apis/networking.istio.io/v1alpha3/namespaces/#{namespace}/gateways/#{name}")
      .to_return(kube_response(kube_istio_gateway_body(name, namespace)))
  end

  def stub_kubeclient_put_gateway(api_url, name, namespace: 'default')
    WebMock.stub_request(:put, api_url + "/apis/networking.istio.io/v1alpha3/namespaces/#{namespace}/gateways/#{name}")
      .to_return(kube_response({}))
  end

250
  def kube_v1_secret_body(**options)
251 252 253
    {
      "kind" => "SecretList",
      "apiVersion": "v1",
254
      "metadata": {
255
        "name": options.fetch(:metadata_name, "default-token-1"),
256 257 258
        "namespace": "kube-system"
      },
      "data": {
259
        "token": options.fetch(:token, Base64.encode64('token-sample-123'))
260
      }
261 262 263
    }
  end

264
  def kube_v1_discovery_body
265 266
    {
      "kind" => "APIResourceList",
267
      "resources" => [
268
        { "name" => "pods", "namespaced" => true, "kind" => "Pod" },
269
        { "name" => "deployments", "namespaced" => true, "kind" => "Deployment" },
270
        { "name" => "secrets", "namespaced" => true, "kind" => "Secret" },
271
        { "name" => "serviceaccounts", "namespaced" => true, "kind" => "ServiceAccount" },
272 273
        { "name" => "services", "namespaced" => true, "kind" => "Service" },
        { "name" => "namespaces", "namespaced" => true, "kind" => "Namespace" }
274 275 276 277 278 279 280 281 282 283
      ]
    }
  end

  def kube_v1beta1_discovery_body
    {
      "kind" => "APIResourceList",
      "resources" => [
        { "name" => "pods", "namespaced" => true, "kind" => "Pod" },
        { "name" => "deployments", "namespaced" => true, "kind" => "Deployment" },
284
        { "name" => "secrets", "namespaced" => true, "kind" => "Secret" },
285
        { "name" => "serviceaccounts", "namespaced" => true, "kind" => "ServiceAccount" },
286 287 288 289 290 291 292 293 294 295 296 297 298
        { "name" => "services", "namespaced" => true, "kind" => "Service" }
      ]
    }
  end

  def kube_v1_rbac_authorization_discovery_body
    {
      "kind" => "APIResourceList",
      "resources" => [
        { "name" => "clusterrolebindings", "namespaced" => false, "kind" => "ClusterRoleBinding" },
        { "name" => "clusterroles", "namespaced" => false, "kind" => "ClusterRole" },
        { "name" => "rolebindings", "namespaced" => true, "kind" => "RoleBinding" },
        { "name" => "roles", "namespaced" => true, "kind" => "Role" }
299
      ]
300 301 302
    }
  end

303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
  def kube_istio_discovery_body
    {
      "kind" => "APIResourceList",
      "apiVersion" => "v1",
      "groupVersion" => "networking.istio.io/v1alpha3",
      "resources" => [
        {
          "name" => "gateways",
          "singularName" => "gateway",
          "namespaced" => true,
          "kind" => "Gateway",
          "verbs" => %w[delete deletecollection get list patch create update watch],
          "shortNames" => %w[gw],
          "categories" => %w[istio-io networking-istio-io]
        },
        {
          "name" => "serviceentries",
          "singularName" => "serviceentry",
          "namespaced" => true,
          "kind" => "ServiceEntry",
          "verbs" => %w[delete deletecollection get list patch create update watch],
          "shortNames" => %w[se],
          "categories" => %w[istio-io networking-istio-io]
        },
        {
          "name" => "destinationrules",
          "singularName" => "destinationrule",
          "namespaced" => true,
          "kind" => "DestinationRule",
          "verbs" => %w[delete deletecollection get list patch create update watch],
          "shortNames" => %w[dr],
          "categories" => %w[istio-io networking-istio-io]
        },
        {
          "name" => "envoyfilters",
          "singularName" => "envoyfilter",
          "namespaced" => true,
          "kind" => "EnvoyFilter",
          "verbs" => %w[delete deletecollection get list patch create update watch],
          "categories" => %w[istio-io networking-istio-io]
        },
        {
          "name" => "sidecars",
          "singularName" => "sidecar",
          "namespaced" => true,
          "kind" => "Sidecar",
          "verbs" => %w[delete deletecollection get list patch create update watch],
          "categories" => %w[istio-io networking-istio-io]
        },
        {
          "name" => "virtualservices",
          "singularName" => "virtualservice",
          "namespaced" => true,
          "kind" => "VirtualService",
          "verbs" => %w[delete deletecollection get list patch create update watch],
          "shortNames" => %w[vs],
          "categories" => %w[istio-io networking-istio-io]
        }
      ]
    }
  end

  def kube_istio_gateway_body(name, namespace)
    {
      "apiVersion" => "networking.istio.io/v1alpha3",
      "kind" => "Gateway",
      "metadata" => {
        "generation" => 1,
        "labels" => {
          "networking.knative.dev/ingress-provider" => "istio",
          "serving.knative.dev/release" => "v0.7.0"
        },
        "name" => name,
        "namespace" => namespace,
        "selfLink" => "/apis/networking.istio.io/v1alpha3/namespaces/#{namespace}/gateways/#{name}"
      },
      "spec" => {
        "selector" => {
          "istio" => "ingressgateway"
        },
        "servers" => [
          {
            "hosts" => [
              "*"
            ],
            "port" => {
              "name" => "http",
              "number" => 80,
              "protocol" => "HTTP"
            }
          },
          {
            "hosts" => [
              "*"
            ],
            "port" => {
              "name" => "https",
              "number" => 443,
              "protocol" => "HTTPS"
            },
            "tls" => {
              "mode" => "PASSTHROUGH"
            }
          }
        ]
      }
    }
  end

412 413 414 415 416 417 418 419 420 421 422 423
  def kube_v1alpha1_serving_knative_discovery_body
    {
      "kind" => "APIResourceList",
      "resources" => [
        { "name" => "revisions", "namespaced" => true, "kind" => "Revision" },
        { "name" => "services", "namespaced" => true, "kind" => "Service" },
        { "name" => "configurations", "namespaced" => true, "kind" => "Configuration" },
        { "name" => "routes", "namespaced" => true, "kind" => "Route" }
      ]
    }
  end

424 425 426 427 428
  def kube_pods_body
    {
      "kind" => "PodList",
      "items" => [kube_pod]
    }
429 430
  end

431
  def kube_logs_body
432
    "2019-12-13T14:04:22.123456Z Log 1\n2019-12-13T14:04:23.123456Z Log 2\n2019-12-13T14:04:24.123456Z Log 3"
433 434
  end

435 436 437 438 439 440 441
  def kube_deployments_body
    {
      "kind" => "DeploymentList",
      "items" => [kube_deployment]
    }
  end

442 443 444 445 446 447 448
  def kube_knative_pods_body(name, namespace)
    {
      "kind" => "PodList",
      "items" => [kube_knative_pod(name: name, namespace: namespace)]
    }
  end

449
  def kube_knative_services_body(**options)
450 451
    {
      "kind" => "List",
452
      "items" => [knative_09_service(options)]
453 454 455
    }
  end

456 457
  # This is a partial response, it will have many more elements in reality but
  # these are the ones we care about at the moment
458
  def kube_pod(name: "kube-pod", environment_slug: "production", namespace: "project-namespace", project_slug: "project-path-slug", status: "Running", track: nil)
459 460
    {
      "metadata" => {
461
        "name" => name,
462
        "namespace" => namespace,
463
        "generate_name" => "generated-name-with-suffix",
464
        "creationTimestamp" => "2016-11-25T19:55:19Z",
465 466 467 468
        "annotations" => {
          "app.gitlab.com/env" => environment_slug,
          "app.gitlab.com/app" => project_slug
        },
469 470
        "labels" => {
          "track" => track
471
        }.compact
472 473 474 475
      },
      "spec" => {
        "containers" => [
          { "name" => "container-0" },
476 477
          { "name" => "container-1" }
        ]
478
      },
479 480 481 482
      "status" => { "phase" => status }
    }
  end

483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
  # Similar to a kube_pod, but should contain a running service
  def kube_knative_pod(name: "kube-pod", namespace: "default", status: "Running")
    {
      "metadata" => {
        "name" => name,
        "namespace" => namespace,
        "generate_name" => "generated-name-with-suffix",
        "creationTimestamp" => "2016-11-25T19:55:19Z",
        "labels" => {
          "serving.knative.dev/service" => name
        }
      },
      "spec" => {
        "containers" => [
          { "name" => "container-0" },
          { "name" => "container-1" }
        ]
      },
      "status" => { "phase" => status }
    }
  end

505
  def kube_deployment(name: "kube-deployment", environment_slug: "production", project_slug: "project-path-slug", track: nil)
506 507 508 509
    {
      "metadata" => {
        "name" => name,
        "generation" => 4,
510 511 512 513
        "annotations" => {
          "app.gitlab.com/env" => environment_slug,
          "app.gitlab.com/app" => project_slug
        },
514 515 516 517 518 519 520 521 522 523 524
        "labels" => {
          "track" => track
        }.compact
      },
      "spec" => { "replicas" => 3 },
      "status" => {
        "observedGeneration" => 4,
        "replicas" => 3,
        "updatedReplicas" => 3,
        "availableReplicas" => 3
      }
525 526 527
    }
  end

528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
  # noinspection RubyStringKeysInHashInspection
  def knative_06_service(name: 'kubetest', namespace: 'default', domain: 'example.com', description: 'a knative service', environment: 'production')
    { "apiVersion" => "serving.knative.dev/v1alpha1",
      "kind" => "Service",
      "metadata" =>
        { "annotations" =>
            { "serving.knative.dev/creator" => "system:serviceaccount:#{namespace}:#{namespace}-service-account",
              "serving.knative.dev/lastModifier" => "system:serviceaccount:#{namespace}:#{namespace}-service-account" },
          "creationTimestamp" => "2019-10-22T21:19:20Z",
          "generation" => 1,
          "labels" => { "service" => name },
          "name" => name,
          "namespace" => namespace,
          "resourceVersion" => "6042",
          "selfLink" => "/apis/serving.knative.dev/v1alpha1/namespaces/#{namespace}/services/#{name}",
          "uid" => "9c7f63d0-f511-11e9-8815-42010a80002f" },
544
      "spec" => {
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
        "runLatest" => {
          "configuration" => {
            "revisionTemplate" => {
              "metadata" => {
                "annotations" => { "Description" => description },
                "creationTimestamp" => "2019-10-22T21:19:20Z",
                "labels" => { "service" => name }
              },
              "spec" => {
                "container" => {
                  "env" => [{ "name" => "timestamp", "value" => "2019-10-22 21:19:20" }],
                  "image" => "image_name",
                  "name" => "",
                  "resources" => {}
                },
                "timeoutSeconds" => 300
              }
            }
          }
        }
565 566
      },
      "status" => {
567
        "address" => {
568 569
          "hostname" => "#{name}.#{namespace}.svc.cluster.local",
          "url" => "http://#{name}.#{namespace}.svc.cluster.local"
570
        },
571 572 573 574
        "conditions" =>
          [{ "lastTransitionTime" => "2019-10-22T21:20:25Z", "status" => "True", "type" => "ConfigurationsReady" },
           { "lastTransitionTime" => "2019-10-22T21:20:25Z", "status" => "True", "type" => "Ready" },
           { "lastTransitionTime" => "2019-10-22T21:20:25Z", "status" => "True", "type" => "RoutesReady" }],
575 576
        "domain" => "#{name}.#{namespace}.#{domain}",
        "domainInternal" => "#{name}.#{namespace}.svc.cluster.local",
577 578 579 580 581
        "latestCreatedRevisionName" => "#{name}-bskx6",
        "latestReadyRevisionName" => "#{name}-bskx6",
        "observedGeneration" => 1,
        "traffic" => [{ "latestRevision" => true, "percent" => 100, "revisionName" => "#{name}-bskx6" }],
        "url" => "http://#{name}.#{namespace}.#{domain}"
582
      },
583 584 585 586 587 588 589
      "environment_scope" => environment,
      "cluster_id" => 9,
      "podcount" => 0 }
  end

  # noinspection RubyStringKeysInHashInspection
  def knative_07_service(name: 'kubetest', namespace: 'default', domain: 'example.com', description: 'a knative service', environment: 'production')
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
    { "apiVersion" => "serving.knative.dev/v1alpha1",
      "kind" => "Service",
      "metadata" =>
        { "annotations" =>
            { "serving.knative.dev/creator" => "system:serviceaccount:#{namespace}:#{namespace}-service-account",
              "serving.knative.dev/lastModifier" => "system:serviceaccount:#{namespace}:#{namespace}-service-account" },
          "creationTimestamp" => "2019-10-22T21:19:13Z",
          "generation" => 1,
          "labels" => { "service" => name },
          "name" => name,
          "namespace" => namespace,
          "resourceVersion" => "289726",
          "selfLink" => "/apis/serving.knative.dev/v1alpha1/namespaces/#{namespace}/services/#{name}",
          "uid" => "988349fa-f511-11e9-9ea1-42010a80005e" },
      "spec" => {
        "template" => {
          "metadata" => {
            "annotations" => { "Description" => description },
            "creationTimestamp" => "2019-10-22T21:19:12Z",
            "labels" => { "service" => name }
          },
          "spec" => {
            "containers" => [{
                               "env" =>
                                 [{ "name" => "timestamp", "value" => "2019-10-22 21:19:12" }],
                               "image" => "image_name",
                               "name" => "user-container",
                               "resources" => {}
                             }],
            "timeoutSeconds" => 300
          }
        },
        "traffic" => [{ "latestRevision" => true, "percent" => 100 }]
      },
      "status" =>
        { "address" => { "url" => "http://#{name}.#{namespace}.svc.cluster.local" },
          "conditions" =>
            [{ "lastTransitionTime" => "2019-10-22T21:20:15Z", "status" => "True", "type" => "ConfigurationsReady" },
             { "lastTransitionTime" => "2019-10-22T21:20:15Z", "status" => "True", "type" => "Ready" },
             { "lastTransitionTime" => "2019-10-22T21:20:15Z", "status" => "True", "type" => "RoutesReady" }],
          "latestCreatedRevisionName" => "#{name}-92tsj",
          "latestReadyRevisionName" => "#{name}-92tsj",
          "observedGeneration" => 1,
          "traffic" => [{ "latestRevision" => true, "percent" => 100, "revisionName" => "#{name}-92tsj" }],
          "url" => "http://#{name}.#{namespace}.#{domain}" },
      "environment_scope" => environment,
      "cluster_id" => 5,
      "podcount" => 0 }
  end

  # noinspection RubyStringKeysInHashInspection
  def knative_09_service(name: 'kubetest', namespace: 'default', domain: 'example.com', description: 'a knative service', environment: 'production')
642 643 644 645 646 647 648 649 650 651 652 653 654 655
    { "apiVersion" => "serving.knative.dev/v1alpha1",
      "kind" => "Service",
      "metadata" =>
        { "annotations" =>
            { "serving.knative.dev/creator" => "system:serviceaccount:#{namespace}:#{namespace}-service-account",
              "serving.knative.dev/lastModifier" => "system:serviceaccount:#{namespace}:#{namespace}-service-account" },
          "creationTimestamp" => "2019-10-22T21:19:13Z",
          "generation" => 1,
          "labels" => { "service" => name },
          "name" => name,
          "namespace" => namespace,
          "resourceVersion" => "289726",
          "selfLink" => "/apis/serving.knative.dev/v1alpha1/namespaces/#{namespace}/services/#{name}",
          "uid" => "988349fa-f511-11e9-9ea1-42010a80005e" },
656
      "spec" => {
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
        "template" => {
          "metadata" => {
            "annotations" => { "Description" => description },
            "creationTimestamp" => "2019-10-22T21:19:12Z",
            "labels" => { "service" => name }
          },
          "spec" => {
            "containers" => [{
                               "env" =>
                                 [{ "name" => "timestamp", "value" => "2019-10-22 21:19:12" }],
                               "image" => "image_name",
                               "name" => "user-container",
                               "resources" => {}
                             }],
            "timeoutSeconds" => 300
          }
        },
        "traffic" => [{ "latestRevision" => true, "percent" => 100 }]
      },
      "status" =>
        { "address" => { "url" => "http://#{name}.#{namespace}.svc.cluster.local" },
          "conditions" =>
            [{ "lastTransitionTime" => "2019-10-22T21:20:15Z", "status" => "True", "type" => "ConfigurationsReady" },
             { "lastTransitionTime" => "2019-10-22T21:20:15Z", "status" => "True", "type" => "Ready" },
             { "lastTransitionTime" => "2019-10-22T21:20:15Z", "status" => "True", "type" => "RoutesReady" }],
          "latestCreatedRevisionName" => "#{name}-92tsj",
          "latestReadyRevisionName" => "#{name}-92tsj",
          "observedGeneration" => 1,
          "traffic" => [{ "latestRevision" => true, "percent" => 100, "revisionName" => "#{name}-92tsj" }],
          "url" => "http://#{name}.#{namespace}.#{domain}" },
      "environment_scope" => environment,
      "cluster_id" => 5,
      "podcount" => 0 }
  end

  # noinspection RubyStringKeysInHashInspection
  def knative_05_service(name: 'kubetest', namespace: 'default', domain: 'example.com', description: 'a knative service', environment: 'production')
    { "apiVersion" => "serving.knative.dev/v1alpha1",
      "kind" => "Service",
      "metadata" =>
        { "annotations" =>
            { "serving.knative.dev/creator" => "system:serviceaccount:#{namespace}:#{namespace}-service-account",
              "serving.knative.dev/lastModifier" => "system:serviceaccount:#{namespace}:#{namespace}-service-account" },
          "creationTimestamp" => "2019-10-22T21:19:19Z",
          "generation" => 1,
          "labels" => { "service" => name },
          "name" => name,
          "namespace" => namespace,
          "resourceVersion" => "330390",
          "selfLink" => "/apis/serving.knative.dev/v1alpha1/namespaces/#{namespace}/services/#{name}",
          "uid" => "9c710da6-f511-11e9-9ba0-42010a800161" },
      "spec" => {
        "runLatest" => {
          "configuration" => {
            "revisionTemplate" => {
              "metadata" => {
                "annotations" => { "Description" => description },
                "creationTimestamp" => "2019-10-22T21:19:19Z",
                "labels" => { "service" => name }
              },
              "spec" => {
                "container" => {
                  "env" => [{ "name" => "timestamp", "value" => "2019-10-22 21:19:19" }],
                  "image" => "image_name",
                  "name" => "",
                  "resources" => { "requests" => { "cpu" => "400m" } }
                },
                "timeoutSeconds" => 300
              }
            }
          }
728 729
        }
      },
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
      "status" =>
        { "address" => { "hostname" => "#{name}.#{namespace}.svc.cluster.local" },
          "conditions" =>
            [{ "lastTransitionTime" => "2019-10-22T21:20:24Z", "status" => "True", "type" => "ConfigurationsReady" },
             { "lastTransitionTime" => "2019-10-22T21:20:24Z", "status" => "True", "type" => "Ready" },
             { "lastTransitionTime" => "2019-10-22T21:20:24Z", "status" => "True", "type" => "RoutesReady" }],
          "domain" => "#{name}.#{namespace}.#{domain}",
          "domainInternal" => "#{name}.#{namespace}.svc.cluster.local",
          "latestCreatedRevisionName" => "#{name}-58qgr",
          "latestReadyRevisionName" => "#{name}-58qgr",
          "observedGeneration" => 1,
          "traffic" => [{ "percent" => 100, "revisionName" => "#{name}-58qgr" }] },
      "environment_scope" => environment,
      "cluster_id" => 8,
      "podcount" => 0 }
745 746
  end

747 748
  def kube_terminals(service, pod)
    pod_name = pod['metadata']['name']
749
    pod_namespace = pod['metadata']['namespace']
750 751 752 753 754
    containers = pod['spec']['containers']

    containers.map do |container|
      terminal = {
        selectors: { pod: pod_name, container: container['name'] },
755
        url:  container_exec_url(service.api_url, pod_namespace, pod_name, container['name']),
756 757
        subprotocols: ['channel.k8s.io'],
        headers: { 'Authorization' => ["Bearer #{service.token}"] },
758 759
        created_at: DateTime.parse(pod['metadata']['creationTimestamp']),
        max_session_time: 0
760 761 762 763 764
      }
      terminal[:ca_pem] = service.ca_pem if service.ca_pem.present?
      terminal
    end
  end
765 766 767 768 769 770

  def kube_deployment_rollout_status
    ::Gitlab::Kubernetes::RolloutStatus.from_deployments(kube_deployment)
  end

  def empty_deployment_rollout_status
771
    ::Gitlab::Kubernetes::RolloutStatus.from_deployments
772
  end
773
end