Class: Environment

Inherits:
ApplicationRecord show all
Includes:
FastDestroyAll::Helpers, FromUnion, Gitlab::Utils::StrongMemoize, NullifyIfBlank, Presentable, ReactiveCaching
Defined in:
app/models/environment.rb

Constant Summary

Constants included from ReactiveCaching

ReactiveCaching::ExceededReactiveCacheLimit, ReactiveCaching::InvalidateReactiveCache, ReactiveCaching::WORK_TYPE

Constants inherited from ApplicationRecord

ApplicationRecord::MAX_PLUCK

Constants included from ResetOnUnionError

ResetOnUnionError::MAX_RESET_PERIOD

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Presentable

#present

Methods included from FastDestroyAll::Helpers

#perform_fast_destroy

Methods included from AfterCommitQueue

#run_after_commit, #run_after_commit_or_now

Methods inherited from ApplicationRecord

cached_column_list, #create_or_load_association, declarative_enum, default_select_columns, id_in, id_not_in, iid_in, pluck_primary_key, primary_key_in, #readable_by?, safe_ensure_unique, safe_find_or_create_by, safe_find_or_create_by!, #to_ability_name, underscore, where_exists, where_not_exists, with_fast_read_statement_timeout, without_order

Methods included from SensitiveSerializableHash

#serializable_hash

Class Method Details

.count_by_stateObject



249
250
251
252
253
254
255
# File 'app/models/environment.rb', line 249

def count_by_state
  environments_count_by_state = group(:state).count

  valid_states.index_with do |state|
    environments_count_by_state[state.to_s] || 0
  end
end

.find_or_create_by_name(name) ⇒ Object



230
231
232
# File 'app/models/environment.rb', line 230

def self.find_or_create_by_name(name)
  find_or_create_by(name: name)
end

.for_id_and_slug(id, slug) ⇒ Object



211
212
213
# File 'app/models/environment.rb', line 211

def self.for_id_and_slug(id, slug)
  find_by(id: id, slug: slug)
end

.max_deployment_id_queryObject



215
216
217
218
219
220
# File 'app/models/environment.rb', line 215

def self.max_deployment_id_query
  Arel.sql(
    Deployment.select(Deployment.arel_table[:id].maximum)
    .where(Deployment.arel_table[:environment_id].eq(arel_table[:id])).to_sql
  )
end

.nestedObject



242
243
244
245
246
# File 'app/models/environment.rb', line 242

def self.nested
  group('COALESCE(environment_type, id::text)', 'COALESCE(environment_type, name)')
    .select('COALESCE(environment_type, id::text), COALESCE(environment_type, name) AS name', 'COUNT(*) AS size', 'MAX(id) AS last_id')
    .order('name ASC')
end

.pluck_namesObject



222
223
224
# File 'app/models/environment.rb', line 222

def self.pluck_names
  pluck(:name)
end

.pluck_unique_namesObject



226
227
228
# File 'app/models/environment.rb', line 226

def self.pluck_unique_names
  pluck('DISTINCT(environments.name)')
end

.schedule_to_delete(at_time = 1.week.from_now) ⇒ Object



238
239
240
# File 'app/models/environment.rb', line 238

def self.schedule_to_delete(at_time = 1.week.from_now)
  update_all(auto_delete_at: at_time)
end

.valid_statesObject



234
235
236
# File 'app/models/environment.rb', line 234

def self.valid_states
  self.state_machine.states.map(&:name)
end

Instance Method Details

#actions_for(environment) ⇒ Object



386
387
388
389
390
391
392
# File 'app/models/environment.rb', line 386

def actions_for(environment)
  return [] unless manual_actions

  manual_actions.select do |action|
    action.expanded_environment_name == environment
  end
end

#additional_metrics(*args) ⇒ Object



436
437
438
439
440
# File 'app/models/environment.rb', line 436

def additional_metrics(*args)
  return unless has_metrics_and_can_query?

  prometheus_adapter.query(:additional_metrics_environment, self, *args.map(&:to_f))
end

#auto_stop_inObject



491
492
493
# File 'app/models/environment.rb', line 491

def auto_stop_in
  auto_stop_at - Time.current if auto_stop_at
end

#auto_stop_in=(value) ⇒ Object



495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
# File 'app/models/environment.rb', line 495

def auto_stop_in=(value)
  if value.nil?
    # Handles edge case when auto_stop_at is already set and the new value is nil.
    # Possible by setting `auto_stop_in: null` in the CI configuration yml.
    self.auto_stop_at = nil

    return
  end

  parser = ::Gitlab::Ci::Build::DurationParser.new(value)

  self.auto_stop_at = parser.seconds_from_now
rescue ChronicDuration::DurationParseError => ex
  Gitlab::ErrorTracking.track_exception(ex, project_id: self.project_id, environment_id: self.id)
  raise ex
end

#calculate_reactive_cacheObject



404
405
406
407
408
# File 'app/models/environment.rb', line 404

def calculate_reactive_cache
  return unless has_terminals? && !project.pending_delete?

  deployment_platform.calculate_reactive_cache_for(self)
end

#cancel_deployment_jobs!Object



335
336
337
338
339
340
341
342
343
# File 'app/models/environment.rb', line 335

def cancel_deployment_jobs!
  active_deployments.jobs.each do |job|
    Gitlab::OptimisticLocking.retry_lock(job, name: 'environment_cancel_deployment_jobs') do |job|
      job.cancel! if job&.cancelable?
    end
  rescue StandardError => e
    Gitlab::ErrorTracking.track_exception(e, environment_id: id, deployment_id: deployment.id)
  end
end

#clear_all_cachesObject



532
533
534
535
# File 'app/models/environment.rb', line 532

def clear_all_caches
  expire_etag_cache
  clear_reactive_cache!
end

#clear_prometheus_reactive_cache!(query_name) ⇒ Object



287
288
289
# File 'app/models/environment.rb', line 287

def clear_prometheus_reactive_cache!(query_name)
  cluster_prometheus_adapter&.clear_prometheus_reactive_cache!(query_name, self)
end

#cluster_prometheus_adapterObject



291
292
293
# File 'app/models/environment.rb', line 291

def cluster_prometheus_adapter
  @cluster_prometheus_adapter ||= ::Gitlab::Prometheus::Adapter.new(project, deployment_platform&.cluster).cluster_prometheus_adapter
end

#deploy_freezesObject



545
546
547
548
549
# File 'app/models/environment.rb', line 545

def deploy_freezes
  Gitlab::SafeRequestStore.fetch("project:#{project_id}:freeze_periods_for_environments") do
    project.freeze_periods
  end
end

#deployment_namespaceObject



410
411
412
413
414
# File 'app/models/environment.rb', line 410

def deployment_namespace
  strong_memoize(:kubernetes_namespace) do
    deployment_platform.cluster.kubernetes_namespace_for(self) if deployment_platform
  end
end

#deployment_platformObject



479
480
481
482
483
# File 'app/models/environment.rb', line 479

def deployment_platform
  strong_memoize(:deployment_platform) do
    project.deployment_platform(environment: self.name)
  end
end

#etag_cache_keyObject



465
466
467
468
469
# File 'app/models/environment.rb', line 465

def etag_cache_key
  Gitlab::Routing.url_helpers.project_environments_path(
    project,
    format: :json)
end

#expire_etag_cacheObject



459
460
461
462
463
# File 'app/models/environment.rb', line 459

def expire_etag_cache
  Gitlab::EtagCaching::Store.new.tap do |store|
    store.touch(etag_cache_key)
  end
end

#external_url_for(path, commit_sha) ⇒ Object



450
451
452
453
454
455
456
457
# File 'app/models/environment.rb', line 450

def external_url_for(path, commit_sha)
  return unless self.external_url

  public_path = project.public_path_for_source_path(path, commit_sha)
  return unless public_path

  [external_url.delete_suffix('/'), public_path.delete_prefix('/')].join('/')
end

#folder_nameObject



471
472
473
# File 'app/models/environment.rb', line 471

def folder_name
  self.environment_type || self.name
end

#for_name_likeObject

Search environments which have names like the given query. Do not set a large limit unless you’ve confirmed that it works on gitlab.com scale.



132
133
134
135
136
# File 'app/models/environment.rb', line 132

scope :for_name_like, -> (query, limit: 5) do
  top_level = 'LOWER(environments.name) LIKE LOWER(?) || \'%\''

  where(top_level, sanitize_sql_like(query)).limit(limit)
end

#formatted_external_urlObject



325
326
327
328
329
# File 'app/models/environment.rb', line 325

def formatted_external_url
  return unless external_url

  external_url.gsub(%r{\A.*?://}, '')
end

#has_metrics?Boolean

Returns:

  • (Boolean)


416
417
418
# File 'app/models/environment.rb', line 416

def has_metrics?
  available? && (prometheus_adapter&.configured? || has_sample_metrics?)
end

#has_opened_alert?Boolean

Returns:

  • (Boolean)


424
425
426
# File 'app/models/environment.rb', line 424

def has_opened_alert?
  latest_opened_most_severe_alert.present?
end

#has_running_deployments?Boolean

Returns:

  • (Boolean)


428
429
430
# File 'app/models/environment.rb', line 428

def has_running_deployments?
  all_deployments.running.exists?
end

#has_sample_metrics?Boolean

Returns:

  • (Boolean)


420
421
422
# File 'app/models/environment.rb', line 420

def has_sample_metrics?
  !!ENV['USE_SAMPLE_METRICS']
end

#has_terminals?Boolean

Returns:

  • (Boolean)


394
395
396
# File 'app/models/environment.rb', line 394

def has_terminals?
  available? && deployment_platform.present? && last_deployment.present?
end

#includes_commit?(sha) ⇒ Boolean

Returns:

  • (Boolean)


311
312
313
314
315
# File 'app/models/environment.rb', line 311

def includes_commit?(sha)
  return false unless last_deployment

  last_deployment.includes_commit?(sha)
end

#ingressesObject



520
521
522
523
524
# File 'app/models/environment.rb', line 520

def ingresses
  return unless rollout_status_available?

  deployment_platform.ingresses(deployment_namespace)
end

#knative_services_finderObject



485
486
487
488
489
# File 'app/models/environment.rb', line 485

def knative_services_finder
  if last_deployment&.cluster
    Clusters::KnativeServicesFinder.new(last_deployment.cluster, self)
  end
end

#last_deployableObject



258
259
260
# File 'app/models/environment.rb', line 258

def last_deployable
  last_deployment&.deployable
end

#last_deployed_atObject



317
318
319
# File 'app/models/environment.rb', line 317

def last_deployed_at
  last_deployment.try(:created_at)
end

#last_deployment_groupObject



378
379
380
# File 'app/models/environment.rb', line 378

def last_deployment_group
  Deployment.last_deployment_group_for_environment(self)
end

#last_deployment_pipelineObject



262
263
264
# File 'app/models/environment.rb', line 262

def last_deployment_pipeline
  last_deployable&.pipeline
end

#last_visible_deployableObject



279
280
281
# File 'app/models/environment.rb', line 279

def last_visible_deployable
  last_visible_deployment&.deployable
end

#last_visible_pipelineObject



283
284
285
# File 'app/models/environment.rb', line 283

def last_visible_pipeline
  last_visible_deployable&.pipeline
end

#legacy_last_deployment_groupObject

This method returns the deployment records of the last deployment pipeline, that successfully executed to this environment. e.g. A pipeline contains

- deploy job A => production environment
- deploy job B => production environment

In this case, ‘last_deployment_group` returns both deployments, whereas `last_deployable` returns only B.



272
273
274
275
276
277
# File 'app/models/environment.rb', line 272

def legacy_last_deployment_group
  return Deployment.none unless last_deployment_pipeline

  successful_deployments.where(
    deployable_id: last_deployment_pipeline.latest_builds.pluck(:id))
end

#metricsObject



432
433
434
# File 'app/models/environment.rb', line 432

def metrics
  prometheus_adapter.query(:environment, self) if has_metrics_and_can_query?
end

#name_without_typeObject



475
476
477
# File 'app/models/environment.rb', line 475

def name_without_type
  @name_without_type ||= name.delete_prefix("#{environment_type}/")
end

#patch_ingress(ingress, data) ⇒ Object



526
527
528
529
530
# File 'app/models/environment.rb', line 526

def patch_ingress(ingress, data)
  return unless rollout_status_available?

  deployment_platform.patch_ingress(deployment_namespace, ingress, data)
end

#predefined_variablesObject



295
296
297
298
299
# File 'app/models/environment.rb', line 295

def predefined_variables
  Gitlab::Ci::Variables::Collection.new
    .append(key: 'CI_ENVIRONMENT_NAME', value: name)
    .append(key: 'CI_ENVIRONMENT_SLUG', value: slug)
end

#prometheus_adapterObject



442
443
444
# File 'app/models/environment.rb', line 442

def prometheus_adapter
  @prometheus_adapter ||= Gitlab::Prometheus::Adapter.new(project, deployment_platform&.cluster).prometheus_adapter
end

#recently_updated_on_branch?(ref) ⇒ Boolean

Returns:

  • (Boolean)


301
302
303
# File 'app/models/environment.rb', line 301

def recently_updated_on_branch?(ref)
  ref.to_s == last_deployment.try(:ref)
end

#ref_pathObject



321
322
323
# File 'app/models/environment.rb', line 321

def ref_path
  "refs/#{Repository::REF_ENVIRONMENTS}/#{slug}"
end

#reset_auto_stopObject



382
383
384
# File 'app/models/environment.rb', line 382

def reset_auto_stop
  update_column(:auto_stop_at, nil)
end

#rollout_statusObject



512
513
514
515
516
517
518
# File 'app/models/environment.rb', line 512

def rollout_status
  return unless rollout_status_available?

  result = rollout_status_with_reactive_cache

  result || ::Gitlab::Kubernetes::RolloutStatus.loading
end

#set_environment_typeObject



305
306
307
308
309
# File 'app/models/environment.rb', line 305

def set_environment_type
  names = name.split('/')

  self.environment_type = names.many? ? names.first : nil
end

Returns:

  • (Boolean)


537
538
539
# File 'app/models/environment.rb', line 537

def should_link_to_merge_requests?
  unfoldered? || production? || staging?
end

#slugObject



446
447
448
# File 'app/models/environment.rb', line 446

def slug
  super.presence || generate_slug
end

#stop_actionsObject



372
373
374
375
376
# File 'app/models/environment.rb', line 372

def stop_actions
  strong_memoize(:stop_actions) do
    last_deployment_group.map(&:stop_action).compact
  end
end

#stop_actions_available?Boolean

Returns:

  • (Boolean)


331
332
333
# File 'app/models/environment.rb', line 331

def stop_actions_available?
  available? && stop_actions.present?
end

#stop_with_actions!(current_user) ⇒ Object



349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'app/models/environment.rb', line 349

def stop_with_actions!(current_user)
  return unless available?

  stop!

  actions = []

  stop_actions.each do |stop_action|
    Gitlab::OptimisticLocking.retry_lock(
      stop_action,
      name: 'environment_stop_with_actions'
    ) do |job|
      actions << job.play(current_user)
    rescue StateMachines::InvalidTransition
      # Ci::PlayBuildService rescues an error of StateMachines::InvalidTransition and fall back to retry. However,
      # Ci::PlayBridgeService doesn't rescue it, so we're ignoring the error if it's not playable.
      # We should fix this inconsistency in https://gitlab.com/gitlab-org/gitlab/-/issues/420855.
    end
  end

  actions
end

#terminalsObject



398
399
400
401
402
# File 'app/models/environment.rb', line 398

def terminals
  with_reactive_cache do |data|
    deployment_platform.terminals(self, data)
  end
end

#unfoldered?Boolean

Returns:

  • (Boolean)


541
542
543
# File 'app/models/environment.rb', line 541

def unfoldered?
  environment_type.nil?
end

#wait_for_stop?Boolean

Returns:

  • (Boolean)


345
346
347
# File 'app/models/environment.rb', line 345

def wait_for_stop?
  stop_actions.present?
end