Class: KubernetesDeploy::DeployTask

Inherits:
Object
  • Object
show all
Extended by:
StatsD::MeasureMethods
Defined in:
lib/kubernetes-deploy/deploy_task.rb

Overview

Ship resources to a namespace

Direct Known Subclasses

Krane::DeployTask

Constant Summary collapse

PROTECTED_NAMESPACES =
%w(
  default
  kube-system
  kube-public
)

Instance Method Summary collapse

Methods included from StatsD::MeasureMethods

measure_method

Constructor Details

#initialize(namespace:, context:, current_sha:, logger: nil, kubectl_instance: nil, bindings: {}, max_watch_seconds: nil, selector: nil, template_paths: [], template_dir: nil, protected_namespaces: nil, render_erb: true, allow_globals: false) ⇒ DeployTask

Initializes the deploy task

Parameters:

  • namespace (String)

    Kubernetes namespace

  • context (String)

    Kubernetes context

  • current_sha (String)

    The SHA of the commit

  • logger (Object) (defaults to: nil)

    Logger object (defaults to an instance of KubernetesDeploy::FormattedLogger)

  • kubectl_instance (Kubectl) (defaults to: nil)

    Kubectl instance

  • bindings (Hash) (defaults to: {})

    Bindings parsed by KubernetesDeploy::BindingsParser

  • max_watch_seconds (Integer) (defaults to: nil)

    Timeout in seconds

  • selector (Hash) (defaults to: nil)

    Selector(s) parsed by KubernetesDeploy::LabelSelector

  • template_paths (Array<String>) (defaults to: [])

    An array of template paths

  • template_dir (String) (defaults to: nil)

    Path to a directory with templates (deprecated)

  • protected_namespaces (Array<String>) (defaults to: nil)

    Array of protected Kubernetes namespaces (defaults to KubernetesDeploy::DeployTask::PROTECTED_NAMESPACES)

  • render_erb (Boolean) (defaults to: true)

    Enable ERB rendering



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/kubernetes-deploy/deploy_task.rb', line 125

def initialize(namespace:, context:, current_sha:, logger: nil, kubectl_instance: nil, bindings: {},
  max_watch_seconds: nil, selector: nil, template_paths: [], template_dir: nil, protected_namespaces: nil,
  render_erb: true, allow_globals: false)
  template_dir = File.expand_path(template_dir) if template_dir
  template_paths = (template_paths.map { |path| File.expand_path(path) } << template_dir).compact

  @logger = logger || KubernetesDeploy::FormattedLogger.build(namespace, context)
  @template_sets = TemplateSets.from_dirs_and_files(paths: template_paths, logger: @logger)
  @task_config = KubernetesDeploy::TaskConfig.new(context, namespace, @logger)
  @bindings = bindings
  @namespace = namespace
  @namespace_tags = []
  @context = context
  @current_sha = current_sha
  @kubectl = kubectl_instance
  @max_watch_seconds = max_watch_seconds
  @selector = selector
  @protected_namespaces = protected_namespaces || PROTECTED_NAMESPACES
  @render_erb = render_erb
  @allow_globals = allow_globals
end

Instance Method Details

#predeploy_sequenceObject

Things removed from default prune whitelist at github.com/kubernetes/kubernetes/blob/0dff56b4d88ec7551084bf89028dbeebf569620e/pkg/kubectl/cmd/apply.go#L411: core/v1/Namespace – not namespaced core/v1/PersistentVolume – not namespaced core/v1/Endpoints – managed by services core/v1/PersistentVolumeClaim – would delete data core/v1/ReplicationController – superseded by deployments/replicasets



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/kubernetes-deploy/deploy_task.rb', line 62

def predeploy_sequence
  before_crs = %w(
    ResourceQuota
    NetworkPolicy
  )
  after_crs = %w(
    ConfigMap
    PersistentVolumeClaim
    ServiceAccount
    Role
    RoleBinding
    Secret
    Pod
  )

  before_crs + cluster_resource_discoverer.crds.select(&:predeployed?).map(&:kind) + after_crs
end

#prune_whitelistObject



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/kubernetes-deploy/deploy_task.rb', line 80

def prune_whitelist
  wl = %w(
    core/v1/ConfigMap
    core/v1/Pod
    core/v1/Service
    core/v1/ResourceQuota
    core/v1/Secret
    core/v1/ServiceAccount
    core/v1/PodTemplate
    core/v1/PersistentVolumeClaim
    batch/v1/Job
    apps/v1/ReplicaSet
    apps/v1/DaemonSet
    apps/v1/Deployment
    extensions/v1beta1/Ingress
    networking.k8s.io/v1/NetworkPolicy
    apps/v1/StatefulSet
    autoscaling/v1/HorizontalPodAutoscaler
    policy/v1beta1/PodDisruptionBudget
    batch/v1beta1/CronJob
    rbac.authorization.k8s.io/v1/Role
    rbac.authorization.k8s.io/v1/RoleBinding
  )
  wl + cluster_resource_discoverer.crds.select(&:prunable?).map(&:group_version_kind)
end

#run(*args) ⇒ Boolean

Runs the task, returning a boolean representing success or failure

Returns:

  • (Boolean)


150
151
152
153
154
155
# File 'lib/kubernetes-deploy/deploy_task.rb', line 150

def run(*args)
  run!(*args)
  true
rescue FatalDeploymentError
  false
end

#run!(verify_result: true, allow_protected_ns: false, prune: true) ⇒ nil

Runs the task, raising exceptions in case of issues

Parameters:

  • verify_result (Boolean) (defaults to: true)

    Wait for completion and verify success

  • allow_protected_ns (Boolean) (defaults to: false)

    Enable deploying to protected namespaces

  • prune (Boolean) (defaults to: true)

    Enable deletion of resources that do not appear in the template dir

Returns:

  • (nil)


164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/kubernetes-deploy/deploy_task.rb', line 164

def run!(verify_result: true, allow_protected_ns: false, prune: true)
  start = Time.now.utc
  @logger.reset

  @logger.phase_heading("Initializing deploy")
  validate_configuration(allow_protected_ns: allow_protected_ns, prune: prune)
  resources = discover_resources
  validate_resources(resources)

  @logger.phase_heading("Checking initial resource statuses")
  check_initial_status(resources)

  if deploy_has_priority_resources?(resources)
    @logger.phase_heading("Predeploying priority resources")
    predeploy_priority_resources(resources)
  end

  @logger.phase_heading("Deploying all resources")
  if @protected_namespaces.include?(@namespace) && prune
    raise FatalDeploymentError, "Refusing to deploy to protected namespace '#{@namespace}' with pruning enabled"
  end

  if verify_result
    deploy_all_resources(resources, prune: prune, verify: true)
    failed_resources = resources.reject(&:deploy_succeeded?)
    success = failed_resources.empty?
    if !success && failed_resources.all?(&:deploy_timed_out?)
      raise DeploymentTimeoutError
    end
    raise FatalDeploymentError unless success
  else
    deploy_all_resources(resources, prune: prune, verify: false)
    @logger.summary.add_action("deployed #{resources.length} #{'resource'.pluralize(resources.length)}")
    warning = <<~MSG
      Deploy result verification is disabled for this deploy.
      This means the desired changes were communicated to Kubernetes, but the deploy did not make sure they actually succeeded.
    MSG
    @logger.summary.add_paragraph(ColorizedString.new(warning).yellow)
  end
  StatsD.event("Deployment of #{@namespace} succeeded",
    "Successfully deployed all #{@namespace} resources to #{@context}",
    alert_type: "success", tags: statsd_tags << "status:success")
  StatsD.distribution('all_resources.duration', StatsD.duration(start), tags: statsd_tags << "status:success")
  @logger.print_summary(:success)
rescue DeploymentTimeoutError
  @logger.print_summary(:timed_out)
  StatsD.event("Deployment of #{@namespace} timed out",
    "One or more #{@namespace} resources failed to deploy to #{@context} in time",
    alert_type: "error", tags: statsd_tags << "status:timeout")
  StatsD.distribution('all_resources.duration', StatsD.duration(start), tags: statsd_tags << "status:timeout")
  raise
rescue FatalDeploymentError => error
  @logger.summary.add_action(error.message) if error.message != error.class.to_s
  @logger.print_summary(:failure)
  StatsD.event("Deployment of #{@namespace} failed",
    "One or more #{@namespace} resources failed to deploy to #{@context}",
    alert_type: "error", tags: statsd_tags << "status:failed")
  StatsD.distribution('all_resources.duration', StatsD.duration(start), tags: statsd_tags << "status:failed")
  raise
end

#server_versionObject



106
107
108
# File 'lib/kubernetes-deploy/deploy_task.rb', line 106

def server_version
  kubectl.server_version
end