Class: Environment

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

Constant Summary collapse

LONG_STOP =
1.week

Constants included from CacheMarkdownField

CacheMarkdownField::INVALIDATED_BY

Constants included from ReactiveCaching

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

Constants inherited from ApplicationRecord

ApplicationRecord::MAX_PLUCK

Constants included from HasCheckConstraints

HasCheckConstraints::NOT_NULL_CHECK_PATTERN

Constants included from ResetOnColumnErrors

ResetOnColumnErrors::MAX_RESET_PERIOD

Instance Attribute Summary

Attributes included from CacheMarkdownField

#skip_markdown_cache_validation

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 included from CacheMarkdownField

#attribute_invalidated?, #banzai_render_context, #cached_html_for, #cached_html_up_to_date?, #can_cache_field?, #invalidated_markdown_cache?, #latest_cached_markdown_version, #mentionable_attributes_changed?, #mentioned_filtered_user_ids_for, #parent_user, #refresh_markdown_cache, #refresh_markdown_cache!, #rendered_field_content, #skip_project_check?, #store_mentions!, #store_mentions?, #store_mentions_after_commit?, #updated_cached_html_for

Methods inherited from ApplicationRecord

===, cached_column_list, #create_or_load_association, current_transaction, declarative_enum, default_select_columns, delete_all_returning, #deleted_from_database?, id_in, id_not_in, iid_in, nullable_column?, primary_key_in, #readable_by?, safe_ensure_unique, safe_find_or_create_by, safe_find_or_create_by!, sharding_keys, #to_ability_name, underscore, where_exists, where_not_exists, with_fast_read_statement_timeout, without_order

Methods included from ResetOnColumnErrors

#reset_on_union_error, #reset_on_unknown_attribute_error

Methods included from Gitlab::SensitiveSerializableHash

#serializable_hash

Class Method Details

.count_by_stateObject



279
280
281
282
283
284
285
# File 'app/models/environment.rb', line 279

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



260
261
262
# File 'app/models/environment.rb', line 260

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

.for_id_and_slug(id, slug) ⇒ Object



241
242
243
# File 'app/models/environment.rb', line 241

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

.max_deployment_id_queryObject



245
246
247
248
249
250
# File 'app/models/environment.rb', line 245

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



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

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



252
253
254
# File 'app/models/environment.rb', line 252

def self.pluck_names
  pluck(:name)
end

.pluck_unique_namesObject



256
257
258
# File 'app/models/environment.rb', line 256

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

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



268
269
270
# File 'app/models/environment.rb', line 268

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

.valid_statesObject



264
265
266
# File 'app/models/environment.rb', line 264

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

Instance Method Details

#actions_for(environment) ⇒ Object



411
412
413
414
415
416
417
# File 'app/models/environment.rb', line 411

def actions_for(environment)
  return [] unless manual_actions

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

#auto_stop_inObject



498
499
500
# File 'app/models/environment.rb', line 498

def auto_stop_in
  auto_stop_at - Time.current if auto_stop_at
end

#auto_stop_in=(value) ⇒ Object



502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
# File 'app/models/environment.rb', line 502

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



429
430
431
432
433
# File 'app/models/environment.rb', line 429

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

  deployment_platform.calculate_reactive_cache_for(self)
end

#cancel_deployment_jobs!Object



365
366
367
368
369
370
371
372
373
# File 'app/models/environment.rb', line 365

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



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

def clear_all_caches
  expire_etag_cache
  clear_reactive_cache!
end

#clear_prometheus_reactive_cache!(query_name) ⇒ Object



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

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

#cluster_prometheus_adapterObject



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

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

#deploy_freezesObject



552
553
554
555
556
# File 'app/models/environment.rb', line 552

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

#deployment_namespaceObject



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

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

#deployment_platformObject



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

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

#ensure_environment_tierObject



558
559
560
# File 'app/models/environment.rb', line 558

def ensure_environment_tier
  self.tier ||= guess_tier
end

#etag_cache_keyObject



472
473
474
475
476
# File 'app/models/environment.rb', line 472

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

#expire_etag_cacheObject



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

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



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

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



478
479
480
# File 'app/models/environment.rb', line 478

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.



154
155
156
157
158
# File 'app/models/environment.rb', line 154

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



355
356
357
358
359
# File 'app/models/environment.rb', line 355

def formatted_external_url
  return unless external_url

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

#has_opened_alert?Boolean

Returns:

  • (Boolean)


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

def has_opened_alert?
  latest_opened_most_severe_alert.present?
end

#has_running_deployments?Boolean

Returns:

  • (Boolean)


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

def has_running_deployments?
  all_deployments.running.exists?
end

#has_terminals?Boolean

Returns:

  • (Boolean)


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

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

#includes_commit?(sha) ⇒ Boolean

Returns:

  • (Boolean)


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

def includes_commit?(sha)
  return false unless last_deployment

  last_deployment.includes_commit?(sha)
end

#ingressesObject



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

def ingresses
  return unless rollout_status_available?

  deployment_platform.ingresses(deployment_namespace)
end

#knative_services_finderObject



492
493
494
495
496
# File 'app/models/environment.rb', line 492

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

#last_deployableObject



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

def last_deployable
  last_deployment&.deployable
end

#last_deployed_atObject



343
344
345
# File 'app/models/environment.rb', line 343

def last_deployed_at
  last_deployment.try(:created_at)
end

#last_finished_deployableObject



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

def last_finished_deployable
  last_finished_deployment&.deployable
end

#last_finished_deployment_groupObject



403
404
405
# File 'app/models/environment.rb', line 403

def last_finished_deployment_group
  Deployment.last_finished_deployment_group_for_environment(self)
end

#last_finished_pipelineObject



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

def last_finished_pipeline
  last_finished_deployable&.pipeline
end

#last_visible_deployableObject



304
305
306
# File 'app/models/environment.rb', line 304

def last_visible_deployable
  last_visible_deployment&.deployable
end

#last_visible_pipelineObject



308
309
310
# File 'app/models/environment.rb', line 308

def last_visible_pipeline
  last_visible_deployable&.pipeline
end

#latest_finished_jobsObject



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

def latest_finished_jobs
  last_finished_pipeline&.latest_finished_jobs
end

#long_stopping?Boolean

Returns:

  • (Boolean)


347
348
349
# File 'app/models/environment.rb', line 347

def long_stopping?
  stopping? && self.updated_at < LONG_STOP.ago
end

#name_without_typeObject



482
483
484
# File 'app/models/environment.rb', line 482

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

#patch_ingress(ingress, data) ⇒ Object



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

def patch_ingress(ingress, data)
  return unless rollout_status_available?

  deployment_platform.patch_ingress(deployment_namespace, ingress, data)
end

#predefined_variablesObject



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

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

#prometheus_adapterObject



449
450
451
# File 'app/models/environment.rb', line 449

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

#recently_updated_on_branch?(ref) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#ref_pathObject



351
352
353
# File 'app/models/environment.rb', line 351

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

#reset_auto_stopObject



407
408
409
# File 'app/models/environment.rb', line 407

def reset_auto_stop
  update_column(:auto_stop_at, nil)
end

#rollout_statusObject



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

def rollout_status
  return unless rollout_status_available?

  result = rollout_status_with_reactive_cache

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

#set_default_auto_stop_settingObject



562
563
564
565
566
567
568
# File 'app/models/environment.rb', line 562

def set_default_auto_stop_setting
  self.auto_stop_setting = if Feature.enabled?(:new_default_for_auto_stop, project)
                             production? || staging? ? :with_action : :always
                           else
                             :always
                           end
end

#set_environment_typeObject



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

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

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

Returns:

  • (Boolean)


544
545
546
# File 'app/models/environment.rb', line 544

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

#slugObject



453
454
455
# File 'app/models/environment.rb', line 453

def slug
  super.presence || generate_slug
end

#stop_actionsObject



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

def stop_actions
  last_finished_deployment_group.map(&:stop_action).compact
end

#stop_actions_available?Boolean

Returns:

  • (Boolean)


361
362
363
# File 'app/models/environment.rb', line 361

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

#stop_with_actions!Object

TODO: move this method and dependencies into Environments::StopService



380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
# File 'app/models/environment.rb', line 380

def stop_with_actions!
  return unless available?

  if stop_actions.any? || auto_stop_setting_always?
    stop!
  end

  # The current_user stopping the environment may not be the same actor that we use
  # to run the stop action jobs. We need to ensure that if any of the actors require
  # composite identity we link it before hand.
  # This design assumes that all `stop_actions` have the same user.
  link_identity = ::Gitlab::Auth::Identity.currently_linked.blank?

  stop_actions.filter_map do |stop_action|
    run_stop_action!(stop_action, link_identity: link_identity)
  end
end

#terminalsObject



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

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

#unfoldered?Boolean

Returns:

  • (Boolean)


548
549
550
# File 'app/models/environment.rb', line 548

def unfoldered?
  environment_type.nil?
end

#wait_for_stop?Boolean

Returns:

  • (Boolean)


375
376
377
# File 'app/models/environment.rb', line 375

def wait_for_stop?
  stop_actions.present?
end