diff --git a/lib/stackbuilder/stacks/custom_services.rb b/lib/stackbuilder/stacks/custom_services.rb index 70108989..91374158 100644 --- a/lib/stackbuilder/stacks/custom_services.rb +++ b/lib/stackbuilder/stacks/custom_services.rb @@ -24,7 +24,8 @@ def identity end def service_in_kubernetes?(name, properties) - fail("app_service '#{name}' does not specify kubernetes property for environment '#{@environment.name}'. \ + caller_name = caller[0][/`([^']*)'/, 1] + fail("#{caller_name} '#{name}' does not specify kubernetes property for environment '#{@environment.name}'. \ If any environments are specified then all environments where the stack is instantiated must \ be specified.") if properties.is_a?(Hash) && properties[:kubernetes].is_a?(Hash) && !properties[:kubernetes].key?(@environment.name) @@ -38,13 +39,21 @@ def service_in_kubernetes?(name, properties) def app_service(name, properties = {}, &block) if service_in_kubernetes?(name, properties) - k8s_machineset_with(name, [Stacks::Services::VirtualService, Stacks::Services::AppService], &block) + k8s_machineset_with(name, [Stacks::Services::VirtualService, Stacks::Services::BaseK8sApp, Stacks::Services::AppService], &block) else machineset_with(name, [Stacks::Services::VirtualService, Stacks::Services::AppService], Stacks::Services::AppServer, &block) end end + def base_service(name, properties = {}, &block) + if service_in_kubernetes?(name, properties) + k8s_machineset_with(name, [Stacks::Services::VirtualService, Stacks::Services::BaseK8sApp], &block) + else + fail 'base_service outside of Kubernetes is not implemented' + end + end + def standalone_app_service(name, properties = {}, &block) if service_in_kubernetes?(name, properties) k8s_machineset_with(name, [Stacks::Services::AppService], &block) diff --git a/lib/stackbuilder/stacks/dependencies.rb b/lib/stackbuilder/stacks/dependencies.rb index 8a89ead4..9dd8f2f7 100644 --- a/lib/stackbuilder/stacks/dependencies.rb +++ b/lib/stackbuilder/stacks/dependencies.rb @@ -184,4 +184,8 @@ def dependant_instances(location, reject_nodes_in_different_location = true, rej reject_nodes_in_different_location, reject_k8s_nodes) end + + def non_k8s_dependencies_exist? + dependants.count { |dep| !dep.from.kubernetes } > 0 + end end diff --git a/lib/stackbuilder/stacks/environment.rb b/lib/stackbuilder/stacks/environment.rb index b5caf226..b40e3a71 100644 --- a/lib/stackbuilder/stacks/environment.rb +++ b/lib/stackbuilder/stacks/environment.rb @@ -268,4 +268,8 @@ def depend_on(dependant, env = environment.name, requirement = nil) dep = Stacks::Dependencies::EnvironmentDependency.new(self, Stacks::Dependencies::ServiceSelector.new(dependant, env), requirement) @depends_on << dep unless @depends_on.include? dep end + + def kubernetes + false + end end diff --git a/lib/stackbuilder/stacks/kubernetes/config_erb.rb b/lib/stackbuilder/stacks/kubernetes/config_erb.rb new file mode 100644 index 00000000..699f1d2d --- /dev/null +++ b/lib/stackbuilder/stacks/kubernetes/config_erb.rb @@ -0,0 +1,29 @@ +class ConfigERB < ERB + attr_reader :used_secrets + + def initialize(template, vars, hiera_provider) + super(template, nil, '-') + vars.each { |k, v| instance_variable_set("@#{k}", v) } + @vars = vars + @hiera_provider = hiera_provider + @used_secrets = {} + end + + def hiera(key, default = nil) + value = @hiera_provider.lookup(@vars, key, default) + fail "The hiera value for #{key} is encrypted. \ +e secret(#{key}) instead of hiera(#{key}) in appconfig" if value.is_a?(String) && value.match(/^ENC\[GPG/) + value + end + + def secret(key, index = nil) + secret_name = key.gsub(/[^a-zA-Z0-9]/, '_') + secret_name += "_#{index}" unless index.nil? + @used_secrets[key] = secret_name + "{SECRET:#{secret_name}}" + end + + def render + result(binding) + end +end diff --git a/lib/stackbuilder/stacks/kubernetes/namespace.rb b/lib/stackbuilder/stacks/kubernetes/namespace.rb new file mode 100644 index 00000000..786f2332 --- /dev/null +++ b/lib/stackbuilder/stacks/kubernetes/namespace.rb @@ -0,0 +1,7 @@ +module Stacks + module Kubernetes + require 'stackbuilder/stacks/kubernetes/config_erb' + require 'stackbuilder/stacks/kubernetes/resource_set_app' + require 'stackbuilder/stacks/kubernetes/resource_set_ingress' + end +end diff --git a/lib/stackbuilder/stacks/kubernetes/network_policy_common.rb b/lib/stackbuilder/stacks/kubernetes/network_policy_common.rb new file mode 100644 index 00000000..c5c30467 --- /dev/null +++ b/lib/stackbuilder/stacks/kubernetes/network_policy_common.rb @@ -0,0 +1,26 @@ +module Stacks::Kubernetes::NetworkPolicyCommon + def create_egress_network_policy(name, env_name, labels, egresses, pod_selector_match_labels) + spec = { + 'podSelector' => { + 'matchLabels' => pod_selector_match_labels + }, + 'policyTypes' => [ + 'Egress' + ], + 'egress' => egresses + } + + hash = Support::DigestGenerator.from_hash(spec) + + { + 'apiVersion' => 'networking.k8s.io/v1', + 'kind' => 'NetworkPolicy', + 'metadata' => { + 'name' => "allow-out-to-#{name}-#{hash}", + 'namespace' => env_name, + 'labels' => labels + }, + 'spec' => spec + } + end +end diff --git a/lib/stackbuilder/stacks/kubernetes/resource_set_app.rb b/lib/stackbuilder/stacks/kubernetes/resource_set_app.rb new file mode 100644 index 00000000..b723f94e --- /dev/null +++ b/lib/stackbuilder/stacks/kubernetes/resource_set_app.rb @@ -0,0 +1,680 @@ + require 'stackbuilder/stacks/kubernetes/network_policy_common' + require 'stackbuilder/stacks/kubernetes/resource_set_ingress' + + module Stacks::Kubernetes::ResourceSetApp + include Stacks::Kubernetes::NetworkPolicyCommon + include Stacks::Kubernetes::ResourceSetIngress + + ## + # Classes including this module must define the following instance variables + # + # @artifact_from_nexus as true/false + # + # @ports as a hash of hashes detailing the config of each port. + # { + # A string identifier for this port. If your application is a regular service then the name form /etc/services is probably a good choice. + # For our custom applcations serving up http use 'http'. + # 'name' => { + # 'port' => An Integer defining the port number + # 'protocol' => Optional string detailing the protocol of this port. Places in the code should default to TCP if this is undefined. + # 'service_port' => Optional Integer used to create a Kubernetes Service to expose this app + # } + # } + # + # And the following functions + # non_k8s_dependencies_exist? + + def use_service_account + @enable_service_account = true + end + + private + + # rubocop:disable Metrics/ParameterLists + def app_generate_resources(_app_deployer, dns_resolver, hiera_provider, hiera_scope, app_name, app_version, replicas, used_secrets, site, \ + standard_labels, app_service_labels, app_resources_name, config) + # rubocop:enable Metrics/ParameterLists + output = [] + output << generate_app_config_map_resource(app_resources_name, app_service_labels, config) unless config.nil? + output << generate_app_service_resource(app_resources_name, app_service_labels) + output << generate_app_deployment_resource(app_resources_name, app_service_labels, app_name, app_version, replicas, used_secrets, config) + output << generate_app_pod_disruption_budget_resource(app_resources_name, app_service_labels) + output << generate_app_alerting_resource(app_resources_name, site, app_service_labels) + output += generate_app_network_policies(dns_resolver, site, app_service_labels) + output += generate_app_service_account_resources(dns_resolver, site, app_service_labels, app_resources_name) + + output += ingress_generate_resources(dns_resolver, hiera_provider, hiera_scope, site, \ + standard_labels, app_service_labels, app_resources_name, app_resources_name) + + output + end + + def generate_app_config_map_resource(resource_name, labels, config) + { + 'apiVersion' => 'v1', + 'kind' => 'ConfigMap', + 'metadata' => { + 'name' => resource_name, + 'namespace' => @environment.name, + 'labels' => labels + }, + 'data' => { + 'config.properties' => config + } + } + end + + def generate_app_service_resource(resource_name, labels) + { + 'apiVersion' => 'v1', + 'kind' => 'Service', + 'metadata' => { + 'name' => resource_name, + 'namespace' => @environment.name, + 'labels' => labels + }, + 'spec' => { + 'type' => 'ClusterIP', + 'selector' => { + 'machineset' => labels['machineset'], + 'group' => labels['group'], + 'app.kubernetes.io/component' => labels['app.kubernetes.io/component'], + 'participation' => 'enabled' + }, + 'ports' => @ports.keys.select do |port_name| + !@ports[port_name]['service_port'].nil? + end.map do |port_name| + port_config = {} + port_config['name'] = port_name + port_config['port'] = @ports[port_name]['service_port'] + port_config['protocol'] = @ports[port_name]['protocol'].nil? ? 'TCP' : @ports[port_name]['protocol'].upcase + port_config['targetPort'] = @ports[port_name]['port'] + port_config + end + } + } + end + + # rubocop:disable Metrics/AbcSize, Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity + def generate_app_deployment_resource(resource_name, app_service_labels, app_name, app_version, replicas, _secrets, config) + # rubocop:enable Metrics/AbcSize, Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity + + labels = app_service_labels.merge('application' => app_name, + 'app.kubernetes.io/name' => app_name, + 'app.kubernetes.io/version' => app_version) + + container_image = "repo.net.local:8080/timgroup/#{app_name}:#{app_version}" + + annotations = {} + annotations['maintainers'] = JSON.dump(@maintainers) unless @maintainers.empty? + annotations['description'] = description unless @description.nil? + + deployment_annotations = {} + deployment_annotations['configmap.reloader.stakater.com/reload'] = resource_name + deployment_annotations['secret.reloader.stakater.com/reload'] = resource_name + deployment_annotations.merge!(annotations) + + pod_annotations = {} + pod_annotations['seccomp.security.alpha.kubernetes.io/pod'] = 'runtime/default' + pod_annotations.merge!(annotations) + + deployment = { + 'apiVersion' => 'apps/v1', + 'kind' => 'Deployment', + 'metadata' => { + 'name' => resource_name, + 'namespace' => @environment.name, + 'labels' => labels, + 'annotations' => deployment_annotations + }, + 'spec' => { + 'selector' => { + 'matchLabels' => { + 'machineset' => labels['machineset'], + 'group' => labels['group'], + 'app.kubernetes.io/component' => labels['app.kubernetes.io/component'], + 'participation' => 'enabled' + } + }, + 'strategy' => { + 'type' => 'RollingUpdate', + 'rollingUpdate' => { # these settings allow one instance to be taken down and no extras to be created, this replicates orc + 'maxUnavailable' => 1, + 'maxSurge' => 0 + } + }, + 'progressDeadlineSeconds' => startup_alert_threshold_seconds, + 'replicas' => replicas, + 'template' => { + 'metadata' => { + 'labels' => { + 'participation' => 'enabled' + }.merge(labels), + 'annotations' => pod_annotations + }, + 'spec' => { + 'affinity' => { + 'podAntiAffinity' => { + 'preferredDuringSchedulingIgnoredDuringExecution' => [{ + 'podAffinityTerm' => { + 'labelSelector' => { + 'matchLabels' => { + 'machineset' => labels['machineset'], + 'group' => labels['group'], + 'app.kubernetes.io/component' => labels['app.kubernetes.io/component'] + } + }, + 'topologyKey' => 'kubernetes.io/hostname' + }, + 'weight' => 100 + }] + } + }, + 'automountServiceAccountToken' => false, + 'containers' => [{ + 'securityContext' => { + 'readOnlyRootFilesystem' => true, + 'allowPrivilegeEscalation' => false, + 'capabilities' => { + 'drop' => ['ALL'] + } + }, + 'image' => container_image, + 'name' => app_name, + 'resources' => create_app_container_resources_snippet, + 'ports' => @ports.keys.map do |port_name| + port_config = {} + port_config['name'] = port_name + port_config['containerPort'] = @ports[port_name]['port'] + port_config['protocol'] = @ports[port_name][:protocol].nil? ? 'TCP' : @ports[port_name]['protocol'.upcase] + port_config + end, + 'volumeMounts' => [ + { + 'name' => 'tmp-volume', + 'mountPath' => '/tmp' + } + ] + }], + 'volumes' => [ + { + 'name' => 'tmp-volume', + 'emptyDir' => {} + } + ] + } + } + } + } + + if @enable_service_account + deployment['spec']['template']['spec']['automountServiceAccountToken'] = true + deployment['spec']['template']['spec']['serviceAccountName'] = resource_name + end + + deployment['spec']['template']['spec']['securityContext'] = @security_context unless @security_context.nil? + deployment['spec']['template']['spec']['containers'].first['command'] = @command unless @command.nil? + deployment['spec']['template']['spec']['containers'].first['args'] = @args unless @args.nil? + deployment['spec']['template']['spec']['containers'].first['lifecycle'] = { + 'preStop' => @lifecycle_pre_stop + } unless @lifecycle_pre_stop.nil? + deployment['spec']['template']['spec']['containers'].first['readinessProbe'] = @readiness_probe unless @readiness_probe.nil? + deployment['spec']['template']['spec']['containers'].first['volumeMounts'] << + { + 'name' => 'config-volume', + 'mountPath' => '/config', + 'readOnly' => true + } unless config.nil? + deployment['spec']['template']['spec']['containers'].first['volumeMounts'] << + { + 'name' => 'log-volume', + 'mountPath' => @log_volume_mount_path + } unless @log_volume_mount_path.nil? + deployment['spec']['template']['spec']['volumes'] += [{ + 'name' => 'config-volume', + 'emptyDir' => {} + }, + { + 'name' => 'config-template', + 'configMap' => { 'name' => resource_name } + }] unless config.nil? + deployment['spec']['template']['spec']['volumes'] << + { + 'name' => 'log-volume', + 'emptyDir' => {} + + } unless @log_volume_mount_path.nil? + unless @capabilities.nil? + existing_capabilities = deployment['spec']['template']['spec']['containers'].first['securityContext']['capabilities'] + existing_capabilities['add'] = [] if existing_capabilitiest['add'].nil? + @capabilities.each do |capability| + existing_capabilitiest['add'] << capability unless existing_capabilities['add'].include? capability + end + end + + deployment + end + + def generate_app_pod_disruption_budget_resource(resource_name, app_service_labels) + { + 'apiVersion' => 'policy/v1beta1', + 'kind' => 'PodDisruptionBudget', + 'metadata' => { + 'name' => resource_name, + 'namespace' => @environment.name, + 'labels' => app_service_labels + }, + 'spec' => { + 'maxUnavailable' => 1, + 'selector' => { + 'matchLabels' => { + 'machineset' => app_service_labels['machineset'], + 'group' => app_service_labels['group'], + 'app.kubernetes.io/component' => app_service_labels['app.kubernetes.io/component'] + } + } + } + } + end + + def generate_app_alerting_resource(resource_name, site, app_service_labels) + fail("app_service '#{name}' in '#{@environment.name}' requires alerts_channel (set self.alerts_channel)") if @alerts_channel.nil? + + pagerduty = page_on_critical ? { 'pagerduty' => 'true' } : {} + + rules = [] + + rules << { + 'alert' => 'StatusCritical', + 'expr' => "sum(tucker_component_status{job=\"#{resource_name}\",status=\"critical\"}) by (pod, namespace) > 0", + 'labels' => { + 'severity' => 'critical', + 'alertname' => "#{resource_name} CRITICAL", + 'alert_owner_channel' => alerts_channel + }.merge(pagerduty), + 'annotations' => { + 'message' => '{{ $value }} components are critical on {{ $labels.namespace }}/{{ $labels.pod }}', + 'status_page_url' => "https://go.timgroup.com/insight/#{site}/proxy/{{ $labels.namespace }}/{{ $labels.pod }}/info/status" + } + } if @monitor_tucker + + rules << { + 'alert' => 'DeploymentReplicasMismatch', + 'expr' => "kube_deployment_spec_replicas{job='kube-state-metrics', namespace='#{environment.name}', deployment='#{resource_name}'} " \ + "!= kube_deployment_status_replicas_available{job='kube-state-metrics', namespace='#{environment.name}', deployment='#{resource_name}'}", + 'for' => startup_alert_threshold, + 'labels' => { + 'severity' => 'warning', + 'alertname' => "#{resource_name} is missing replicas", + 'alert_owner_channel' => alerts_channel + }, + 'annotations' => { + 'message' => "Deployment {{ $labels.namespace }}/{{ $labels.deployment }} has not matched the " \ + "expected number of replicas for longer than the startup_alert_threshold (#{startup_alert_threshold})." + } + } + + rules << { + 'alert' => 'PodCrashLooping', + 'expr' => "kube_pod_container_status_last_terminated_reason{namespace='#{environment.name}', pod=~'^#{resource_name}.*'} == 1 and " \ + "on(pod, container) rate(kube_pod_container_status_restarts_total[5m]) * 300 > 1", + 'labels' => { + 'severity' => 'critical', + 'alertname' => "#{resource_name} is stuck in a crash loop", + 'alert_owner_channel' => alerts_channel + }.merge(pagerduty), + 'annotations' => { + 'message' => 'Pod {{ $labels.namespace }}/{{ $labels.pod }} ({{ $labels.container }}) is restarting ' \ + '{{ printf "%.2f" $value }} times / 5 minutes.' + } + } + + rules << { + 'alert' => 'ImageRetrievalFailure', + 'expr' => "kube_pod_container_status_waiting_reason{reason=~'^(ErrImagePull|ImagePullBackOff|InvalidImageName)$', " \ + "namespace='#{environment.name}', pod=~'^#{resource_name}.*'} == 1", + 'labels' => { + 'severity' => 'warning', + 'alertname' => "#{resource_name} is failing to retrieve the requested image", + 'alert_owner_channel' => alerts_channel + }, + 'annotations' => { + 'message' => 'Pod {{ $labels.namespace }}/{{ $labels.pod }} ({{ $labels.container }}) is failing to retrieve ' \ + 'the requested image.' + } + } + + if @monitor_readiness_probe + rules << { + 'alert' => 'FailedReadinessProbe', + 'expr' => "(((time() - kube_pod_start_time{pod=~\".*#{resource_name}.*\"}) > #{startup_alert_threshold_seconds}) "\ + "and on(pod) (rate(prober_probe_total{probe_type=\"Readiness\",result=\"failed\",pod=~\"^#{resource_name}.*\"}[1m]) > 0))", + 'labels' => { + 'severity' => 'warning', + 'alertname' => "#{resource_name} failed readiness probe when deployment not in progress", + 'alert_owner_channel' => alerts_channel + }, + 'annotations' => { + 'message' => '{{ $labels.namespace }}/{{ $labels.pod }} has failed readiness probe when deployment not in progress', + 'status_page_url' => "https://go.timgroup.com/insight/#{site}/proxy/#{@environment.name}/{{ $labels.pod }}/info/status" + } + } + end + + { + 'apiVersion' => 'monitoring.coreos.com/v1', + 'kind' => 'PrometheusRule', + 'metadata' => { + 'labels' => { + 'prometheus' => 'main', + 'role' => 'alert-rules' + }.merge(app_service_labels), + 'name' => resource_name, + 'namespace' => @environment.name + }, + 'spec' => { + 'groups' => [ + { + 'name' => 'stacks-alerts', + 'rules' => rules + } + ] + } + } + end + + def generate_app_network_policies(dns_resolver, site, standard_labels) + # this method only does the network policies for the app pods + network_policies = [] + + network_policies += create_network_policies_for_dependants(dns_resolver, site, standard_labels) + network_policies += create_network_policies_for_dependencies(dns_resolver, site, standard_labels) + network_policies += create_app_network_policies_to_nexus(dns_resolver, standard_labels) + network_policies += create_app_network_policies_from_prometheus(standard_labels) + + network_policies + end + + def create_network_policies_for_dependants(_dns_resolver, site, standard_labels) + important_dependants = [] + network_policies = [] + + if non_k8s_dependencies_exist? + ingress_selector = { + 'machineset' => name, + 'group' => @groups.first, + 'app.kubernetes.io/component' => 'ingress' + } + ingress_filters = [generate_pod_and_namespace_selector_filter(@environment.name, ingress_selector)] + network_policies << create_ingress_network_policy_for_internal_service(@environment.short_name, "#{name}-#{@groups.first}-ing", + @environment.name, standard_labels, + ingress_filters) + + important_dependants = dependants.select { |dep| dep.from.kubernetes } + else + important_dependants = dependants + end + + important_dependants.each do |dep| + vs = dep.from + is_same_site = dep.requirement == :same_site + next if is_same_site && !vs.exists_in_site?(vs.environment, site) + + match_labels = { + 'machineset' => vs.name, + 'group' => vs.groups.first, + 'app.kubernetes.io/component' => 'app_service' + } + filters = [generate_pod_and_namespace_selector_filter(vs.environment.name, match_labels)] + network_policies << create_ingress_network_policy_for_internal_service(vs.environment.short_name, vs.short_name, + @environment.name, standard_labels, filters) + end + + network_policies + end + + def generate_app_service_account_resources(dns_resolver, site, standard_labels, service_account_name) + return [] unless @enable_service_account + resources = [{ + 'apiVersion' => 'v1', + 'kind' => 'ServiceAccount', + 'metadata' => { + 'name' => service_account_name, + 'namespace' => @environment.name, + 'labels' => standard_labels + } + }] + + network_policy_spec = { + 'podSelector' => { + 'matchLabels' => { + 'machineset' => standard_labels['machineset'], + 'group' => standard_labels['group'], + 'app.kubernetes.io/component' => 'app_service' + } + }, + 'policyTypes' => [ + 'Egress' + ], + + 'egress' => [{ + 'to' => [{ + 'ipBlock' => { + 'cidr' => "#{dns_resolver.lookup("#{site}-kube-apiserver-vip.mgmt.#{site}.net.local")}/32" + } + }], + 'ports' => [{ + 'protocol' => 'TCP', + 'port' => 6443 + }] + }] + } + + hash = Support::DigestGenerator.from_hash(network_policy_spec) + + resources << { + 'apiVersion' => 'networking.k8s.io/v1', + 'kind' => 'NetworkPolicy', + 'metadata' => { + 'name' => "allow-out-to-#{site}-kubernetes-api-#{hash}", + 'namespace' => @environment.name, + 'labels' => standard_labels + }, + 'spec' => network_policy_spec + } + end + + def create_network_policies_for_dependencies(dns_resolver, site, standard_labels) + network_policies = [] + dependencies.each do |dep| + next if dep.is_a?(Stacks::Dependencies::EnvironmentDependency) + + case dep.to_selector + when Stacks::Dependencies::ServiceSelector + dep.resolve_targets(@environment).each do |vs| + network_policies << create_egress_to_specific_service(vs, dns_resolver, site, standard_labels) + end + when Stacks::Dependencies::AllKubernetesSelector + network_policies << create_egress_network_policy( + 'all', + @environment.name, + standard_labels, + [ + { + 'to' => [{ + 'podSelector' => { + 'matchLabels' => { + 'app.kubernetes.io/component' => 'app_service' + } + }, + 'namespaceSelector' => { + 'matchLabels' => { + 'isStacksEnvironment' => 'true' + } + } + }], + 'ports' => @ports.keys.map do |port_name| + { + 'protocol' => @ports[port_name]['protocol'].nil? ? 'TCP' : @ports[port_name]['protocol'].upcase, + 'port' => port_name + } + end + }], + 'machineset' => standard_labels['machineset'], + 'group' => standard_labels['group'], + 'app.kubernetes.io/component' => 'app_service') + end + end + network_policies + end + + def create_egress_to_specific_service(vs, dns_resolver, site, standard_labels) + fail "Dependency '#{vs.name}' is not supported for k8s - endpoints method is not implemented" if !vs.respond_to?(:endpoints) + + chosen_site_of_vs = vs.exists_in_site?(vs.environment, site) ? site : vs.environment.primary_site + endpoints = vs.endpoints(self, chosen_site_of_vs) + + egresses = [] + if vs.kubernetes + match_labels = { + 'machineset' => vs.name, + 'group' => vs.groups.first, + 'app.kubernetes.io/component' => 'app_service' + } + egresses << { + 'to' => [ + generate_pod_and_namespace_selector_filter(vs.environment.name, match_labels) + ], + 'ports' => [{ + 'protocol' => 'TCP', + 'port' => 'app' + }] + } + else + endpoints.each do |e| + ip_blocks = [] + e[:fqdns].uniq.each do |fqdn| + ip_blocks << { 'ipBlock' => { 'cidr' => "#{dns_resolver.lookup(fqdn)}/32" } } + end + egresses << { + 'to' => ip_blocks, + 'ports' => [{ + 'protocol' => 'TCP', + 'port' => e[:port] + }] + } + end + end + app_service_match_labels = { + 'machineset' => standard_labels['machineset'], + 'group' => standard_labels['group'], + 'app.kubernetes.io/component' => 'app_service' + } + + create_egress_network_policy("#{vs.environment.short_name}-#{vs.short_name}", @environment.name, + standard_labels, egresses, app_service_match_labels) + end + + def create_app_network_policies_to_nexus(dns_resolver, standard_labels) + fail('The class including this module must define instance variable @artifact_from_nexus as true or false, probaly in its configure method') \ + if @artifact_from_nexus.nil? + return [] unless @artifact_from_nexus + network_policies = [] + nexus_filters = [{ + 'to' => [{ 'ipBlock' => { 'cidr' => "#{dns_resolver.lookup('office-nexus-001.mgmt.lon.net.local')}/32" } }], + 'ports' => @ports.keys.map do |_port_name| + { + 'protocol' => 'TCP', + 'port' => 8080 + } + end + }] + ingress_match_labels = { + 'machineset' => standard_labels['machineset'], + 'group' => standard_labels['group'], + 'app.kubernetes.io/component' => 'app_service' + } + network_policies << create_egress_network_policy('off-nexus', @environment.name, standard_labels, + nexus_filters, ingress_match_labels) + end + + def create_app_network_policies_from_prometheus(standard_labels) + network_policies = [] + prom_filters = [generate_pod_and_namespace_selector_filter('monitoring', 'prometheus' => 'main')] + network_policies << create_ingress_network_policy_for_internal_service('mon', 'prom-main', + @environment.name, standard_labels, + prom_filters) + network_policies + end + + def create_ingress_network_policy_for_internal_service(virtual_service_env, virtual_service_name, env_name, labels, filters) + spec = { + 'podSelector' => { + 'matchLabels' => { + 'machineset' => labels['machineset'], + 'group' => labels['group'], + 'app.kubernetes.io/component' => 'app_service' + } + }, + 'policyTypes' => [ + 'Ingress' + ], + 'ingress' => [{ + 'from' => filters, + 'ports' => @ports.keys.map do |port_name| + { + 'protocol' => @ports[port_name]['protocol'].nil? ? 'TCP' : @ports[port_name]['protocol'].upcase, + 'port' => port_name + } + end + }] + } + + hash = Support::DigestGenerator.from_hash(spec) + + { + 'apiVersion' => 'networking.k8s.io/v1', + 'kind' => 'NetworkPolicy', + 'metadata' => { + 'name' => "allow-in-from-#{virtual_service_env}-#{virtual_service_name}-#{hash}", + 'namespace' => env_name, + 'labels' => labels + }, + 'spec' => spec + } + end + + def container_image(app_name, app_version) + "repo.net.local:8080/timgroup/#{app_name}:#{app_version}" + end + + def create_app_container_resources_snippet + ephemeral_storage_limit = @ephemeral_storage_size ? { 'ephemeral-storage' => @ephemeral_storage_size } : {} + + cpu_request = @cpu_request ? { 'cpu' => @cpu_request } : {} + cpu_limit = @cpu_limit ? { 'cpu' => @cpu_limit } : {} + + { + 'limits' => { + 'memory' => scale_memory(memory_limit) + }.merge(ephemeral_storage_limit).merge(cpu_limit), + 'requests' => { + 'memory' => scale_memory(memory_limit) + }.merge(ephemeral_storage_limit).merge(cpu_request) + } + end + + def scale_memory(memory, coeff = 0) + m = memory.match(/^(\d+)(G|M|K)i?$/) + byte_conversion_factor = case m.captures[1].upcase + when 'G' + 1024**3 + when 'M' + 1024**2 + when 'K' + 1024 + end + bytes = (1 + coeff) * m.captures[0].to_i * byte_conversion_factor + "#{(bytes / 1024).floor}Ki" + end + end diff --git a/lib/stackbuilder/stacks/kubernetes/resource_set_ingress.rb b/lib/stackbuilder/stacks/kubernetes/resource_set_ingress.rb new file mode 100644 index 00000000..88a91d15 --- /dev/null +++ b/lib/stackbuilder/stacks/kubernetes/resource_set_ingress.rb @@ -0,0 +1,597 @@ +require 'stackbuilder/stacks/kubernetes/network_policy_common' + +module Stacks::Kubernetes::ResourceSetIngress + include Stacks::Kubernetes::NetworkPolicyCommon + + ## + # Classes including this module must define the following instance variables + # + # @ports as a hash of hashes detailing the config of each port. + # { + # A string identifier for this port. If your application is a regular service then the name form /etc/services is probably a good choice. + # For our custom applcations serving up http use 'http'. + # 'name' => { + # 'port' => An Integer defining the port number + # 'protocol' => Optional string detailing the protocol of this port. Places in the code should default to TCP if this is undefined. + # 'service_port' => Optional Integer used to create a Kubernetes Service to expose this app + # } + # } + # + # And the following functions + # non_k8s_dependencies_exist? + + private + + ## + # Generate all new resources required for an ingree + def ingress_generate_resources(dns_resolver, hiera_provider, hiera_scope, site, \ + standard_labels, app_service_labels, app_resources_name, ingress_resources_name) + return [] unless non_k8s_dependencies_exist? + + masters = hiera_provider.lookup(hiera_scope, "kubernetes/masters/#{site}", []) + + output = [] + + ingress_labels = standard_labels.merge('app.kubernetes.io/component' => 'ingress') + + ingress_resources_name = "#{standard_labels['machineset']}-#{standard_labels['group']}-ing" + + output << generate_ingress_resource(app_resources_name, app_resources_name, app_service_labels) + output << generate_ingress_controller_service_account_resource(ingress_resources_name, ingress_labels) + output << generate_ingress_controller_role_resource(ingress_resources_name, ingress_labels) + output << generate_ingress_controller_role_binding_resource(ingress_resources_name, ingress_labels) + output += generate_ingress_controller_network_policies(ingress_resources_name, ingress_labels, dns_resolver, hiera_provider, hiera_scope, site, masters) + output << generate_ingress_controller_service_resource(ingress_resources_name, ingress_labels, dns_resolver, site) + output << generate_ingress_controller_monitoring_service_resource(ingress_resources_name, ingress_labels) + output << generate_ingress_controller_deployment_resource(ingress_resources_name, ingress_labels) + output << generate_ingress_pod_disruption_budget_resource(ingress_resources_name, ingress_labels) + + output + end + + def generate_ingress_resource(name, app_resource_name, labels) + resource = { + 'metadata' => { + 'name' => name, + 'namespace' => @environment.name, + 'labels' => labels, + 'annotations' => { + 'kubernetes.io/ingress.class' => "traefik-#{labels['machineset']}-#{labels['group']}" + } + } + } + + @ports.keys.map do |port_name| + if port_name == 'http' || port_name == 'app' + resource['apiVersion'] = 'networking.k8s.io/v1beta1' + resource['kind'] = 'Ingress' + resource['spec'] = { + 'rules' => [{ + 'http' => { + 'paths' => [{ + 'path' => '/', + 'backend' => { + 'serviceName' => app_resource_name, + 'servicePort' => @ports[port_name]['service_port'] + } + }] + } + }] + } + else + protocol = @ports[port_name]['protocol'].nil? ? 'tcp' : @ports[port_name]['protocol'] + fail("generate_k8s_ingress doesn't know how to handle port name '#{port_name}' with protocol '#{protocol}'") unless %w(tcp udp).include? protocol + fail('IngressRouteTCP support is not completed') if protocol == 'tcp' + kind = "IngressRoute#{protocol.upcase}" + resource['apiVersion'] = 'traefik.containo.us/v1alpha1' + resource['kind'] = kind + resource['spec'] = { + 'entryPoints' => [ + port_name + ], + 'routes' => [{ + 'services' => [{ + 'name' => app_resource_name, + 'port' => @ports[port_name]['service_port'], + 'kind' => 'Service' + }] + }] + } + end + end + resource + end + + def generate_ingress_controller_service_account_resource(name, ingress_labels) + { + 'apiVersion' => 'v1', + 'kind' => 'ServiceAccount', + 'metadata' => { + 'name' => name, + 'namespace' => @environment.name, + 'labels' => ingress_labels + } + } + end + + def generate_ingress_controller_role_resource(name, ingress_labels) + { + 'kind' => 'Role', + 'apiVersion' => 'rbac.authorization.k8s.io/v1', + 'metadata' => { + 'name' => name, + 'namespace' => @environment.name, + 'labels' => ingress_labels + }, + 'rules' => [ + { + 'apiGroups' => [ + "" + ], + 'resources' => %w(secrets services endpoints), + 'verbs' => %w(get list watch) + }, + { + "apiGroups" => [ + "extensions", + "networking.k8s.io" + ], + "resources" => [ + "ingresses" + ], + "verbs" => %w(get list watch) + }, + { + "apiGroups" => [ + "extensions", + "networking.k8s.io" + ], + "resources" => [ + "ingresses/status" + ], + "verbs" => [ + "update" + ] + }, + { + "apiGroups" => [ + "traefik.containo.us" + ], + "resources" => %w(middlewares ingressroutes traefikservices ingressroutetcps ingressrouteudps tlsoptions tlsstores), + "verbs" => %w(get list watch) + } + ] + } + end + + def generate_ingress_controller_role_binding_resource(name, ingress_labels) + { + 'kind' => 'RoleBinding', + 'apiVersion' => 'rbac.authorization.k8s.io/v1', + 'metadata' => { + 'name' => name, + 'namespace' => @environment.name, + 'labels' => ingress_labels + }, + 'roleRef' => { + 'apiGroup' => 'rbac.authorization.k8s.io', + 'kind' => 'Role', + 'name' => name + }, + 'subjects' => [{ + 'kind' => 'ServiceAccount', + 'name' => name + }] + } + end + + def generate_ingress_controller_network_policies(_name, ingress_labels, dns_resolver, hiera_provider, hiera_scope, site, masters) + network_policies = [] + + app_service_match_labels = { + 'machineset' => ingress_labels['machineset'], + 'group' => 'blue', + 'app.kubernetes.io/component' => 'app_service' + } + egresses = [{ + 'to' => [ + generate_pod_and_namespace_selector_filter(@environment.name, app_service_match_labels) + ], + 'ports' => @ports.keys.map do |port_name| + { + 'protocol' => @ports[port_name]['protocol'].nil? ? 'TCP' : @ports[port_name]['protocol'].upcase, + 'port' => port_name + } + end + }] + ingress_match_labels = { + 'machineset' => ingress_labels['machineset'], + 'group' => 'blue', + 'app.kubernetes.io/component' => 'ingress' + } + network_policies << create_egress_network_policy("#{@environment.short_name}-#{short_name}", @environment.name, + ingress_labels, egresses, ingress_match_labels) + + api_server_egresses = [{ + 'to' => masters.map do |master| + { + 'ipBlock' => { + 'cidr' => "#{dns_resolver.lookup(master)}/32" + } + } + end, + 'ports' => [{ + 'port' => 6443, + 'protocol' => 'TCP' + }] + }] + + network_policies << create_egress_network_policy_for_external_service('api-server', @environment.name, ingress_labels, + api_server_egresses, ingress_match_labels) + + dependants.reject { |dep| dep.from.kubernetes }.each do |dep| + case dep.from + when Stacks::Environment + subnet = hiera_provider.lookup(hiera_scope, "networking/#{site}/prod/range") + fail("For an environment dependency networking/#{site}/prod/range must be defined in hieradata") if subnet.nil? + filters = [{ + 'ipBlock' => { + 'cidr' => subnet + } + }] + network_policies << create_ingress_network_policy_for_external_service(dep.from.short_name, dep.from.short_name, + @environment.name, ingress_labels, filters) + else + vs = dep.from + is_same_site = dep.requirement == :same_site + next if is_same_site && !vs.exists_in_site?(vs.environment, site) + + filters = [] + dependant_vms = vs.children.select { |vm| vm.site == (is_same_site ? site : @environment.primary_site) }.sort_by(&:prod_fqdn) + + dependant_vms.each do |vm| + filters << { + 'ipBlock' => { + 'cidr' => "#{dns_resolver.lookup(vm.qualified_hostname(@environment.primary_network))}/32" + } + } + end + network_policies << create_ingress_network_policy_for_external_service(vs.environment.short_name, vs.short_name, + @environment.name, ingress_labels, filters) + end + end + + prom_filters = [generate_pod_and_namespace_selector_filter('monitoring', 'prometheus' => 'main')] + network_policies << create_ingress_network_policy_to_ingress_for_internal_service('mon', 'prom-main', + @environment.name, ingress_labels, + 'traefik', prom_filters, 'TCP') + + network_policies + end + + def generate_ingress_controller_service_resource(name, ingress_labels, dns_resolver, site) + { + 'apiVersion' => 'v1', + 'kind' => 'Service', + 'metadata' => { + 'labels' => ingress_labels, + 'name' => name, + 'namespace' => @environment.name, + 'annotations' => { + 'metallb.universe.tf/address-pool' => 'prod-static' + } + }, + 'spec' => { + 'type' => 'LoadBalancer', + 'loadBalancerIP' => dns_resolver.lookup(prod_fqdn(site)).to_s, + 'externalTrafficPolicy' => 'Local', + 'selector' => { + 'machineset' => ingress_labels['machineset'], + 'group' => ingress_labels['group'], + 'app.kubernetes.io/component' => 'ingress' + }, + 'ports' => @ports.keys.map do |port_name| + case @ports[port_name]['service_port'] + when 80 + { + 'name' => 'http', + 'port' => 80, + 'protocol' => 'TCP', + 'targetPort' => 'http' + } + else + { + 'name' => port_name, + 'port' => @ports[port_name]['port'], + 'protocol' => @ports[port_name]['protocol'].nil? ? 'TCP' : @ports[port_name]['protocol'].upcase, + 'targetPort' => port_name + } + end + end + } + } + end + + def generate_ingress_controller_monitoring_service_resource(name, ingress_labels) + { + 'apiVersion' => 'v1', + 'kind' => 'Service', + 'metadata' => { + 'labels' => ingress_labels.merge('app.kubernetes.io/component' => 'ingress-monitoring'), + 'name' => "#{name}-mon", + 'namespace' => @environment.name + }, + 'spec' => { + 'clusterIP' => 'None', + 'selector' => { + 'machineset' => ingress_labels['machineset'], + 'group' => ingress_labels['group'], + 'app.kubernetes.io/component' => 'ingress' + }, + 'ports' => [ + { + 'name' => 'traefik', + 'port' => 10254, + 'protocol' => 'TCP', + 'targetPort' => 'traefik' + } + ] + } + } + end + + def generate_ingress_controller_deployment_resource(name, ingress_labels) + ingress_controller_labels = ingress_labels.merge('app.kubernetes.io/name' => 'traefik', + 'application' => 'traefik', + 'app.kubernetes.io/version' => '2.2') + + deployment = { + 'apiVersion' => 'apps/v1', + 'kind' => 'Deployment', + 'metadata' => { + 'name' => name, + 'namespace' => @environment.name, + 'labels' => ingress_controller_labels + }, + 'spec' => { + 'replicas' => 2, + 'selector' => { + 'matchLabels' => { + 'machineset' => ingress_labels['machineset'], + 'group' => ingress_labels['group'], + 'app.kubernetes.io/component' => ingress_labels['app.kubernetes.io/component'] + } + }, + 'template' => { + 'metadata' => { + 'labels' => ingress_controller_labels + }, + 'spec' => { + 'containers' => [ + { + 'args' => [ + "--accesslog", + "--ping", + "--api.insecure", + "--api.dashboard", + "--metrics.prometheus", + "--log.level=DEBUG" + ], + 'image' => 'traefik:v2.2', + 'imagePullPolicy' => 'IfNotPresent', + 'livenessProbe' => { + 'failureThreshold' => 3, + 'httpGet' => { + 'path' => '/ping', + 'port' => 'traefik', + 'scheme' => 'HTTP' + }, + 'initialDelaySeconds' => 10, + 'periodSeconds' => 10, + 'successThreshold' => 1, + 'timeoutSeconds' => 10 + }, + 'name' => 'traefik-ingress-controller', + 'ports' => [ + { + 'containerPort' => 10254, + 'name' => 'traefik', + 'protocol' => 'TCP' + } + ], + 'readinessProbe' => { + 'failureThreshold' => 3, + 'httpGet' => { + 'path' => '/ping', + 'port' => 'traefik', + 'scheme' => 'HTTP' + }, + 'periodSeconds' => 10, + 'successThreshold' => 1, + 'timeoutSeconds' => 10 + }, + 'resources' => { + 'limits' => { + 'cpu' => '300m', + 'memory' => '64Mi' + }, + 'requests' => { + 'cpu' => '200m', + 'memory' => '48Mi' + } + }, + 'terminationMessagePath' => '/dev/termination-log', + 'terminationMessagePolicy' => 'File' + } + ], + 'serviceAccountName' => name, + 'terminationGracePeriodSeconds' => 60 + } + } + } + } + + container = deployment['spec']['template']['spec']['containers'].first + container['args'] << "--entrypoints.traefik.Address=:10254" + + @ports.keys.map do |port_name| + actual_port = @ports[port_name]['port'] < 1024 ? 8000 + @ports[port_name]['port'] : @ports[port_name]['port'] + actual_port_name = port_name == 'app' ? 'http' : port_name + container['args'] << "--entrypoints.#{actual_port_name}.Address=:#{actual_port}" + container['ports'] << { + 'containerPort' => actual_port, + 'name' => actual_port_name, + 'protocol' => @ports[port_name]['protocol'].nil? ? 'TCP' : @ports[port_name]['protocol'].upcase + } + + case port_name + when 'app', 'http' + container['args'] << "--entrypoints.#{actual_port_name}.forwardedHeaders.trustedIPs=127.0.0.1/32,10.0.0.0/8" + container['args'] << "--providers.kubernetesingress" + container['args'] << "--providers.kubernetesingress.ingressclass=traefik-#{ingress_labels['machineset']}-#{ingress_labels['group']}" + container['args'] << "--providers.kubernetesingress.ingressendpoint.publishedservice=#{@environment.name}/#{name}" + container['args'] << "--providers.kubernetesingress.namespaces=#{@environment.name}" + else + container['args'] << "--providers.kubernetesCRD" + container['args'] << "--providers.kubernetesCRD.ingressclass=traefik-#{ingress_labels['machineset']}-#{ingress_labels['group']}" + container['args'] << "--providers.kubernetesCRD.namespaces=#{@environment.name}" + end + end + + deployment + end + + def generate_ingress_pod_disruption_budget_resource(name, ingress_labels) + { + 'apiVersion' => 'policy/v1beta1', + 'kind' => 'PodDisruptionBudget', + 'metadata' => { + 'name' => name, + 'namespace' => @environment.name, + 'labels' => ingress_labels + }, + 'spec' => { + 'maxUnavailable' => 1, + 'selector' => { + 'matchLabels' => { + 'machineset' => ingress_labels['machineset'], + 'group' => ingress_labels['group'], + 'app.kubernetes.io/component' => ingress_labels['app.kubernetes.io/component'] + } + } + } + } + end + + def generate_pod_and_namespace_selector_filter(namespace, match_labels) + { + 'podSelector' => { + 'matchLabels' => match_labels + }, + 'namespaceSelector' => { + 'matchLabels' => { + 'name' => namespace + } + } + } + end + + def create_egress_network_policy_for_external_service(service_name, env_name, labels, egresses, pod_selector_match_labels) + spec = { + 'podSelector' => { + 'matchLabels' => pod_selector_match_labels + }, + 'policyTypes' => [ + 'Egress' + ], + 'egress' => egresses + } + + hash = Support::DigestGenerator.from_hash(spec) + + { + 'apiVersion' => 'networking.k8s.io/v1', + 'kind' => 'NetworkPolicy', + 'metadata' => { + 'name' => "allow-out-to-#{service_name}-#{hash}", + 'namespace' => env_name, + 'labels' => labels + }, + 'spec' => spec + } + end + + def create_ingress_network_policy_to_ingress_for_internal_service(virtual_service_env, virtual_service_name, + env_name, labels, port, filters, protocol = 'TCP') + spec = { + 'podSelector' => { + 'matchLabels' => { + 'machineset' => labels['machineset'], + 'group' => labels['group'], + 'app.kubernetes.io/component' => 'ingress' + } + }, + 'policyTypes' => [ + 'Ingress' + ], + 'ingress' => [{ + 'from' => filters, + 'ports' => [{ + 'protocol' => protocol, + 'port' => port + }] + }] + } + + hash = Support::DigestGenerator.from_hash(spec) + + { + 'apiVersion' => 'networking.k8s.io/v1', + 'kind' => 'NetworkPolicy', + 'metadata' => { + 'name' => "allow-in-from-#{virtual_service_env}-#{virtual_service_name}-#{hash}", + 'namespace' => env_name, + 'labels' => labels + }, + 'spec' => spec + } + end + + def create_ingress_network_policy_for_external_service(virtual_service_env, virtual_service_name, env_name, labels, filters) + spec = { + 'podSelector' => { + 'matchLabels' => { + 'machineset' => labels['machineset'], + 'group' => labels['group'], + 'app.kubernetes.io/component' => 'ingress' + } + }, + 'policyTypes' => [ + 'Ingress' + ], + 'ingress' => [{ + 'from' => filters, + 'ports' => @ports.keys.map do |port_name| + port = port_name == 'app' ? 'http' : port_name + { + 'protocol' => @ports[port_name]['protocol'].nil? ? 'TCP' : @ports[port_name]['protocol'].upcase, + 'port' => port + } + end + }] + } + + hash = Support::DigestGenerator.from_hash(spec) + + { + 'apiVersion' => 'networking.k8s.io/v1', + 'kind' => 'NetworkPolicy', + 'metadata' => { + 'name' => "allow-in-from-#{virtual_service_env}-#{virtual_service_name}-#{hash}", + 'namespace' => env_name, + 'labels' => labels + }, + 'spec' => spec + } + end +end diff --git a/lib/stackbuilder/stacks/kubernetes_resource_bundle.rb b/lib/stackbuilder/stacks/kubernetes_resource_bundle.rb index 9cb56048..11554ea1 100644 --- a/lib/stackbuilder/stacks/kubernetes_resource_bundle.rb +++ b/lib/stackbuilder/stacks/kubernetes_resource_bundle.rb @@ -60,7 +60,8 @@ def apply_and_prune(mco_secrets_client) '/v1/Service', '/v1/ServiceAccount', 'monitoring.coreos.com/v1/PrometheusRule', - 'policy/v1beta1/PodDisruptionBudget' + 'policy/v1beta1/PodDisruptionBudget', + 'traefik.containo.us/v1alpha1/IngressRouteUDP' ] rest_mappings_found = @resources.map { |r| r['apiVersion'].include?('/') ? "#{r['apiVersion']}/#{r['kind']}" : "/#{r['apiVersion']}/#{r['kind']}" } diff --git a/lib/stackbuilder/stacks/machine_set.rb b/lib/stackbuilder/stacks/machine_set.rb index e119218a..374675b8 100644 --- a/lib/stackbuilder/stacks/machine_set.rb +++ b/lib/stackbuilder/stacks/machine_set.rb @@ -209,11 +209,12 @@ def allow_host(source_host_or_network) @allowed_hosts.uniq! end - def allow_outbound_to(identifier, destination_ips_in_cidr_form, ports) + def allow_outbound_to(identifier, destination_ips_in_cidr_form, ports, protocol = 'TCP') fail('Allowing outbound connections is only supported if kubernetes is enabled for this machine_set') unless @kubernetes @allowed_outbound_connections[identifier] = { :ips => destination_ips_in_cidr_form.is_a?(Array) ? destination_ips_in_cidr_form : [destination_ips_in_cidr_form], - :ports => ports.is_a?(Array) ? ports : [ports] + :ports => ports.is_a?(Array) ? ports : [ports], + :protocol => protocol } end @@ -263,15 +264,15 @@ def random_name def to_k8s(_app_deployer, _dns_resolver, _hiera_provider, standard_labels) policies = [] - @allowed_outbound_connections.each_key do |outbound_connection| + @allowed_outbound_connections.each do |connection_name, connection_details| filters = [] - @allowed_outbound_connections[outbound_connection][:ips].each do |ip| + connection_details[:ips].each do |ip| filters << { 'ipBlock' => { 'cidr' => ip } } end ports = [] - @allowed_outbound_connections[outbound_connection][:ports].each do |port| + connection_details[:ports].each do |port| ports << { - 'protocol' => 'TCP', + 'protocol' => connection_details[:protocol].nil? ? 'TCP' : connection_details[:protocol], 'port' => port } end @@ -299,7 +300,7 @@ def to_k8s(_app_deployer, _dns_resolver, _hiera_provider, standard_labels) 'apiVersion' => 'networking.k8s.io/v1', 'kind' => 'NetworkPolicy', 'metadata' => { - 'name' => "allow-out-to-#{outbound_connection}-#{hash}", + 'name' => "allow-out-to-#{connection_name}-#{hash}", 'namespace' => @environment.name, 'labels' => { 'stack' => @stack.name, diff --git a/lib/stackbuilder/stacks/services/app_service.rb b/lib/stackbuilder/stacks/services/app_service.rb index 760f5bb8..0caeda71 100644 --- a/lib/stackbuilder/stacks/services/app_service.rb +++ b/lib/stackbuilder/stacks/services/app_service.rb @@ -1,16 +1,12 @@ require 'stackbuilder/stacks/namespace' require 'stackbuilder/stacks/kubernetes_resource_bundle' -require 'stackbuilder/stacks/maintainers' require 'stackbuilder/support/digest_generator' -require 'erb' require 'json' module Stacks::Services::AppService include Stacks::Services::RabbitMqDependent - include Stacks::Maintainers attr_accessor :ajp_port - attr_accessor :application attr_accessor :ehcache attr_accessor :idea_positions_exports attr_accessor :jvm_args @@ -20,21 +16,10 @@ module Stacks::Services::AppService attr_accessor :ha_mysql_ordering_exclude # Kubernetes specific attributes - attr_accessor :appconfig attr_accessor :jvm_heap attr_accessor :headspace - attr_accessor :ephemeral_storage_size - attr_accessor :enable_service_account - attr_accessor :cpu_request - attr_accessor :cpu_limit - - attr_accessor :maintainers - attr_accessor :description - attr_accessor :alerts_channel - attr_accessor :startup_alert_threshold - attr_accessor :monitor_readiness_probe - attr_accessor :page_on_critical + attr_accessor :application alias_method :database_application_name, :application def self.extended(object) @@ -47,7 +32,7 @@ def configure @ehcache = false @idea_positions_exports = false @jvm_args = nil - @ports = [8000] + @ports = { 'app' => { 'port' => 8000, 'service_port' => 80 } } @one_instance_in_lb = false @sso_port = nil @tomcat_session_replication = false @@ -55,13 +40,56 @@ def configure @ha_mysql_ordering_exclude = [] @jvm_heap = '64M' @headspace = 0.1 - @ephemeral_storage_size = nil - @maintainers = [] - @enable_service_account = false - @cpu_request = false - @cpu_limit = false - @monitor_readiness_probe = true - @page_on_critical = false + @artifact_from_nexus = true + @monitor_tucker = true + @security_context = { + 'runAsUser' => 2055, + 'runAsGroup' => 3017, + 'fsGroup' => 3017 + } + @command = ["/bin/sh"] + @args = [ + '-c', + 'exec /usr/bin/java $(cat /config/jvm_args) -jar /app/app.jar /config/config.properties' + ] + @readiness_probe = { + 'periodSeconds' => 2, + 'timeoutSeconds' => 1, + 'failureThreshold' => 6, + 'httpGet' => { + 'path' => '/info/ready', + 'port' => 8000 + } + } + @lifecycle_pre_stop = { + 'exec' => { + 'command' => [ + '/bin/sh', + '-c', + 'sleep 10; while [ "$(curl -s localhost:8000/info/stoppable)" != "safe" ]; do sleep 1; done' + ] + } + } + @log_volume_mount_path = '/var/log/app' + @pre_appconfig_template = <<'EOC' +port=8000 + +log.directory=/var/log/app +log.tags=["env:<%= @logicalenv %>", "app:<%= @application %>", "instance:<%= @group %>"] +<%- if @dependencies.size > 0 -%> +<%- @dependencies.map do |k, v| -%> +<%- if k.start_with?('db.') && k.end_with?('.username') -%> +<%= k %>=<%= v[0,15] + @credentials_selector.to_s %> +<%- elsif k.start_with?('db.') && k.end_with?('password_hiera_key') -%> +<%= k.gsub(/_hiera_key$/, '') %>=<%= secret("#{v}s", @credentials_selector) %> +<%- elsif k.end_with?('_hiera_key') -%> +<%= k.gsub(/_hiera_key$/, '') -%>=<%= secret("#{v}") %> +<%- else -%> +<%= k %>=<%= v %> +<%- end -%> +<%- end -%> +<%- end -%> +EOC end def enable_ehcache @@ -84,19 +112,10 @@ def disable_http_lb_hack @disable_http_lb_hack = true end - def use_service_account - self.enable_service_account = true - end - def rabbitmq_config create_rabbitmq_config(@application) end - def k8s_app_resources_name - group = @groups.first - "#{name}-#{group}-app" - end - def database_username if @kubernetes @environment.short_name + @short_name @@ -148,110 +167,12 @@ def to_loadbalancer_config(location, fabric) config end - class ConfigERB < ERB - attr_reader :used_secrets - - def initialize(template, vars, hiera_provider) - super(template, nil, '-') - vars.each { |k, v| instance_variable_set("@#{k}", v) } - @vars = vars - @hiera_provider = hiera_provider - @used_secrets = {} - end - - def hiera(key, default = nil) - value = @hiera_provider.lookup(@vars, key, default) - fail "The hiera value for #{key} is encrypted. \ -Use secret(#{key}) instead of hiera(#{key}) in appconfig" if value.is_a?(String) && value.match(/^ENC\[GPG/) - value - end - - def secret(key, index = nil) - secret_name = key.gsub(/[^a-zA-Z0-9]/, '_') - secret_name += "_#{index}" unless index.nil? - @used_secrets[key] = secret_name - "{SECRET:#{secret_name}}" - end - - def render - result(binding) - end - end - def assert_k8s_requirements - fail("app_service '#{name}' in '#{@environment.name}' requires maintainers (set self.maintainers)") if @maintainers.empty? - fail("app_service '#{name}' in '#{@environment.name}' requires description (set self.description)") if @description.nil? - fail("app_service '#{name}' in '#{@environment.name}' requires application") if application.nil? - fail('app_service to_k8s doesn\'t know how to deal with multiple groups yet') if @groups.size > 1 - fail('app_service to_k8s doesn\'t know how to deal with @enable_secondary_site yet') if @enable_secondary_site - end - - def to_k8s(app_deployer, dns_resolver, hiera_provider) - assert_k8s_requirements - - instances = if @instances.is_a?(Hash) - @instances - else - { @environment.sites.first => @instances } - end - instances.map do |site, replicas| - app_name = application.downcase - group = @groups.first - - begin - app_version = app_deployer.query_cmdb_for(:application => application, - :environment => @environment.name, - :group => group)[:target_version] - rescue - raise("Version not found in cmdb for application: '#{application}', group: '#{group}' in environment: '#{environment.name}'") - end - - domain = "mgmt.#{environment.domain(site)}" - - hiera_scope = { - 'domain' => domain, - 'hostname' => kubernetes ? identity : children.first.hostname, - 'application' => application, - 'stackname' => @stack.name, - 'logicalenv' => @environment.name, - 'group' => group, - 'site' => site - } - - fake_machine_instance = Struct.new(:index).new(0) - erb_vars = { - 'dependencies' => dependency_config(site, fake_machine_instance), - 'credentials_selector' => hiera_provider.lookup(hiera_scope, 'stacks/application_credentials_selector', nil) - }.merge(hiera_scope) - - standard_labels = { - 'app.kubernetes.io/managed-by' => 'stacks', - 'stack' => @stack.name, - 'machineset' => name, - 'group' => group, - 'app.kubernetes.io/instance' => group, - 'app.kubernetes.io/part-of' => @short_name - } - - app_service_labels = standard_labels.merge('app.kubernetes.io/component' => 'app_service') - - config, used_secrets = generate_app_config(erb_vars, hiera_provider) - - output = super app_deployer, dns_resolver, hiera_provider, app_service_labels - output << generate_k8s_config_map(app_service_labels, config) - output << generate_k8s_service(app_service_labels) - output << generate_k8s_deployment(app_service_labels, app_name, app_version, replicas, used_secrets) - output << generate_k8s_pod_disruption_budget(app_service_labels) - output << generate_k8s_alerting(site, app_service_labels) - output += generate_k8s_network_policies(dns_resolver, site, app_service_labels) - output += generate_k8s_service_account(dns_resolver, site, app_service_labels) - - output += generate_k8s_ingress_resources(dns_resolver, hiera_provider, hiera_scope, site, standard_labels, app_service_labels) - - Stacks::KubernetesResourceBundle.new(site, @environment.name, app_service_labels, output, used_secrets, hiera_scope, k8s_app_resources_name) - end + # FIXME: This isn't right. Other things could technical extend themselves with AppService + super "app_service" end + # FIXME: For some reason this can't move into base_k8s_app?! def prod_fqdn(fabric) if respond_to? :vip_fqdn vip_fqdn(:prod, fabric) @@ -266,1237 +187,80 @@ def instance_name_of(service) "#{service.environment.short_name}-#{service.short_name}" end - def generate_app_config(erb_vars, hiera_provider) - template = <<'EOC' -port=8000 - -log.directory=/var/log/app -log.tags=["env:<%= @logicalenv %>", "app:<%= @application %>", "instance:<%= @group %>"] -<%- if @dependencies.size > 0 -%> -<%- @dependencies.map do |k, v| -%> -<%- if k.start_with?('db.') && k.end_with?('.username') -%> -<%= k %>=<%= v[0,15] + @credentials_selector.to_s %> -<%- elsif k.start_with?('db.') && k.end_with?('password_hiera_key') -%> -<%= k.gsub(/_hiera_key$/, '') %>=<%= secret("#{v}s", @credentials_selector) %> -<%- elsif k.end_with?('_hiera_key') -%> -<%= k.gsub(/_hiera_key$/, '') -%>=<%= secret("#{v}") %> -<%- else -%> -<%= k %>=<%= v %> -<%- end -%> -<%- end -%> -<%- end -%> -EOC - template += appconfig if appconfig - - erb = ConfigERB.new(template, erb_vars, hiera_provider) - contents = erb.render - - [contents, erb.used_secrets] - end - - def generate_k8s_config_map(labels, config) - { - 'apiVersion' => 'v1', - 'kind' => 'ConfigMap', - 'metadata' => { - 'name' => k8s_app_resources_name, - 'namespace' => @environment.name, - 'labels' => labels - }, - 'data' => { - 'config.properties' => config - } - } - end - - def generate_k8s_service(labels) - { - 'apiVersion' => 'v1', - 'kind' => 'Service', - 'metadata' => { - 'name' => k8s_app_resources_name, - 'namespace' => @environment.name, - 'labels' => labels - }, - 'spec' => { - 'type' => 'ClusterIP', - 'selector' => { - 'machineset' => labels['machineset'], - 'group' => labels['group'], - 'app.kubernetes.io/component' => labels['app.kubernetes.io/component'], - 'participation' => 'enabled' - }, - 'ports' => [{ - 'name' => 'app', - 'protocol' => 'TCP', - 'port' => 80, - 'targetPort' => 8000 - }] - } - } + def generate_app_deployment_resource(resource_name, app_service_labels, app_name, app_version, replicas, secrets, config) + deployment = super + deployment['spec']['template']['spec']['initContainers'] = create_init_containers_snippet(secrets, app_name, app_version) + deployment['spec']['template']['spec']['containers'].first['ports'] << { "containerPort" => 5000, "name" => "jmx" } + deployment end - def generate_k8s_deployment(app_service_labels, app_name, app_version, replicas, secrets) - labels = app_service_labels.merge('application' => app_name, - 'app.kubernetes.io/name' => app_name, - 'app.kubernetes.io/version' => app_version) - - container_image = "repo.net.local:8080/timgroup/#{app_name}:#{app_version}" - - annotations = {} - annotations['maintainers'] = JSON.dump(@maintainers) unless @maintainers.empty? - annotations['description'] = description unless @description.nil? - - deployment_annotations = {} - deployment_annotations['configmap.reloader.stakater.com/reload'] = k8s_app_resources_name - deployment_annotations['secret.reloader.stakater.com/reload'] = k8s_app_resources_name - deployment_annotations.merge!(annotations) - - pod_annotations = {} - pod_annotations['seccomp.security.alpha.kubernetes.io/pod'] = 'runtime/default' - pod_annotations.merge!(annotations) - + def create_app_container_resources_snippet ephemeral_storage_limit = @ephemeral_storage_size ? { 'ephemeral-storage' => @ephemeral_storage_size } : {} - if cpu_limit && !cpu_request - fail "You must specify a cpu_request if specifying a cpu_limit" - end - cpu_request = @cpu_request ? { 'cpu' => @cpu_request } : {} cpu_limit = @cpu_limit ? { 'cpu' => @cpu_limit } : {} - deployment = { - 'apiVersion' => 'apps/v1', - 'kind' => 'Deployment', - 'metadata' => { - 'name' => k8s_app_resources_name, - 'namespace' => @environment.name, - 'labels' => labels, - 'annotations' => deployment_annotations - }, - 'spec' => { - 'selector' => { - 'matchLabels' => { - 'machineset' => labels['machineset'], - 'group' => labels['group'], - 'app.kubernetes.io/component' => labels['app.kubernetes.io/component'], - 'participation' => 'enabled' - } - }, - 'strategy' => { - 'type' => 'RollingUpdate', - 'rollingUpdate' => { # these settings allow one instance to be taken down and no extras to be created, this replicates orc - 'maxUnavailable' => 1, - 'maxSurge' => 0 - } - }, - 'progressDeadlineSeconds' => startup_alert_threshold_seconds, - 'replicas' => replicas, - 'template' => { - 'metadata' => { - 'labels' => { - 'participation' => 'enabled' - }.merge(labels), - 'annotations' => pod_annotations - }, - 'spec' => { - 'affinity' => { - 'podAntiAffinity' => { - 'preferredDuringSchedulingIgnoredDuringExecution' => [{ - 'podAffinityTerm' => { - 'labelSelector' => { - 'matchLabels' => { - 'machineset' => labels['machineset'], - 'group' => labels['group'], - 'app.kubernetes.io/component' => labels['app.kubernetes.io/component'] - } - }, - 'topologyKey' => 'kubernetes.io/hostname' - }, - 'weight' => 100 - }] - } - }, - 'automountServiceAccountToken' => false, - 'securityContext' => { - 'runAsUser' => 2055, - 'runAsGroup' => 3017, - 'fsGroup' => 3017 - }, - 'initContainers' => [{ - 'image' => 'repo.net.local:8080/timgroup/config-generator:1.0.5', - 'name' => 'config-generator', - 'env' => secrets.map do |_hiera_key, secret_name| - { - 'name' => "SECRET_#{secret_name}", - 'valueFrom' => { - 'secretKeyRef' => { - 'name' => k8s_app_resources_name, - 'key' => secret_name - } - } - } - end.push( - { - 'name' => 'CONTAINER_IMAGE', - 'value' => container_image - }, - { - 'name' => 'APP_JVM_ARGS', - 'value' => "#{@jvm_args} -Xms#{@jvm_heap} -Xmx#{@jvm_heap}" - }, - { - 'name' => 'BASE_JVM_ARGS', - 'value' => "-Djava.awt.headless=true -Dfile.encoding=UTF-8 -XX:ErrorFile=/var/log/app/error.log " \ - "-XX:HeapDumpPath=/var/log/app -XX:+HeapDumpOnOutOfMemoryError -Djava.security.egd=file:/dev/./urandom " \ - "-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=5000 -Dcom.sun.management.jmxremote.authenticate=false " \ - "-Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.local.only=false " \ - "-Dcom.sun.management.jmxremote.rmi.port=5000 -Djava.rmi.server.hostname=127.0.0.1 " \ - "-Dcom.timgroup.infra.platform=k8s" - }, - { - 'name' => 'GC_JVM_ARGS_JAVA_8', - 'value' => "-XX:+PrintGC -XX:+PrintGCTimeStamps -XX:+PrintGCDateStamps -XX:+PrintGCDetails \ --Xloggc:/var/log/app/gc.log -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=25M \ --XX:+PrintGCApplicationStoppedTime" - }, - 'name' => 'GC_JVM_ARGS_JAVA_11', - 'value' => '-Xlog:gc*,safepoint:/var/log/app/gc.log:time,uptime,level,tags:filecount=10,filesize=26214400' - ), - 'volumeMounts' => [ - { - 'name' => 'config-volume', - 'mountPath' => '/config' - }, - { - 'name' => 'config-template', - 'mountPath' => '/input/config.properties', - 'subPath' => 'config.properties' - }] - }], - 'containers' => [{ - 'securityContext' => { - 'readOnlyRootFilesystem' => true, - 'allowPrivilegeEscalation' => false, - 'capabilities' => { - 'drop' => ['ALL'] - } - }, - 'image' => container_image, - 'name' => app_name, - 'command' => ["/bin/sh"], - 'args' => [ - '-c', - 'exec /usr/bin/java $(cat /config/jvm_args) -jar /app/app.jar /config/config.properties' - ], - 'resources' => { - 'limits' => { - 'memory' => scale_memory(@jvm_heap, @headspace) + 'i' - }.merge(ephemeral_storage_limit).merge(cpu_limit), - 'requests' => { - 'memory' => scale_memory(@jvm_heap, @headspace) + 'i' - }.merge(ephemeral_storage_limit).merge(cpu_request) - }, - 'ports' => [ - { - 'containerPort' => 8000, - 'name' => 'app' - }, - { - 'containerPort' => 5000, - 'name' => 'jmx' - } - ], - 'volumeMounts' => [ - { - 'name' => 'config-volume', - 'mountPath' => '/config', - 'readOnly' => true - }, - { - 'name' => 'log-volume', - 'mountPath' => '/var/log/app' - }, - { - 'name' => 'tmp-volume', - 'mountPath' => '/tmp' - } - ], - 'readinessProbe' => { - 'periodSeconds' => 2, - 'timeoutSeconds' => 1, - 'failureThreshold' => 6, - 'httpGet' => { - 'path' => '/info/ready', - 'port' => 8000 - } - }, - 'lifecycle' => { - 'preStop' => { - 'exec' => { - 'command' => [ - '/bin/sh', - '-c', - 'sleep 10; while [ "$(curl -s localhost:8000/info/stoppable)" != "safe" ]; do sleep 1; done' - ] - } - } - } - }], - 'volumes' => [ - { - 'name' => 'config-volume', - 'emptyDir' => {} - }, - { - 'name' => 'config-template', - 'configMap' => { 'name' => k8s_app_resources_name } - }, - { - 'name' => 'log-volume', - 'emptyDir' => {} - }, - { - 'name' => 'tmp-volume', - 'emptyDir' => {} - } - ] - } - } - } - } - - if enable_service_account - deployment['spec']['template']['spec']['automountServiceAccountToken'] = true - deployment['spec']['template']['spec']['serviceAccountName'] = k8s_app_resources_name - end - - deployment - end - - def generate_k8s_pod_disruption_budget(app_service_labels) - { - 'apiVersion' => 'policy/v1beta1', - 'kind' => 'PodDisruptionBudget', - 'metadata' => { - 'name' => k8s_app_resources_name, - 'namespace' => @environment.name, - 'labels' => app_service_labels - }, - 'spec' => { - 'maxUnavailable' => 1, - 'selector' => { - 'matchLabels' => { - 'machineset' => app_service_labels['machineset'], - 'group' => app_service_labels['group'], - 'app.kubernetes.io/component' => app_service_labels['app.kubernetes.io/component'] - } - } - } - } - end - - def generate_k8s_alerting(site, app_service_labels) - fail("app_service '#{name}' in '#{@environment.name}' requires alerts_channel (set self.alerts_channel)") if @alerts_channel.nil? - - pagerduty = page_on_critical ? { 'pagerduty' => 'true' } : {} - - rules = [] - - rules << { - 'alert' => 'StatusCritical', - 'expr' => "sum(tucker_component_status{job=\"#{k8s_app_resources_name}\",status=\"critical\"}) by (pod, namespace) > 0", - 'labels' => { - 'severity' => 'critical', - 'alertname' => "#{k8s_app_resources_name} CRITICAL", - 'alert_owner_channel' => alerts_channel - }.merge(pagerduty), - 'annotations' => { - 'message' => '{{ $value }} components are critical on {{ $labels.namespace }}/{{ $labels.pod }}', - 'status_page_url' => "https://go.timgroup.com/insight/#{site}/proxy/{{ $labels.namespace }}/{{ $labels.pod }}/info/status" - } - } - - rules << { - 'alert' => 'DeploymentReplicasMismatch', - 'expr' => "kube_deployment_spec_replicas{job='kube-state-metrics', namespace='#{environment.name}', deployment='#{k8s_app_resources_name}'} " \ - "!= kube_deployment_status_replicas_available{job='kube-state-metrics', namespace='#{environment.name}', deployment='#{k8s_app_resources_name}'}", - 'for' => startup_alert_threshold, - 'labels' => { - 'severity' => 'warning', - 'alertname' => "#{k8s_app_resources_name} is missing replicas", - 'alert_owner_channel' => alerts_channel - }, - 'annotations' => { - 'message' => "Deployment {{ $labels.namespace }}/{{ $labels.deployment }} has not matched the " \ - "expected number of replicas for longer than the startup_alert_threshold (#{startup_alert_threshold})." - } - } - - rules << { - 'alert' => 'PodCrashLooping', - 'expr' => "kube_pod_container_status_last_terminated_reason{namespace='#{environment.name}', pod=~'^#{k8s_app_resources_name}.*'} == 1 and " \ - "on(pod, container) rate(kube_pod_container_status_restarts_total[5m]) * 300 > 1", - 'labels' => { - 'severity' => 'critical', - 'alertname' => "#{k8s_app_resources_name} is stuck in a crash loop", - 'alert_owner_channel' => alerts_channel - }.merge(pagerduty), - 'annotations' => { - 'message' => 'Pod {{ $labels.namespace }}/{{ $labels.pod }} ({{ $labels.container }}) is restarting ' \ - '{{ printf "%.2f" $value }} times / 5 minutes.' - } - } - - rules << { - 'alert' => 'ImageRetrievalFailure', - 'expr' => "kube_pod_container_status_waiting_reason{reason=~'^(ErrImagePull|ImagePullBackOff|InvalidImageName)$', " \ - "namespace='#{environment.name}', pod=~'^#{k8s_app_resources_name}.*'} == 1", - 'labels' => { - 'severity' => 'warning', - 'alertname' => "#{k8s_app_resources_name} is failing to retrieve the requested image", - 'alert_owner_channel' => alerts_channel - }, - 'annotations' => { - 'message' => 'Pod {{ $labels.namespace }}/{{ $labels.pod }} ({{ $labels.container }}) is failing to retrieve ' \ - 'the requested image.' - } - } - - if @monitor_readiness_probe - rules << { - 'alert' => 'FailedReadinessProbe', - 'expr' => "(((time() - kube_pod_start_time{pod=~\".*#{k8s_app_resources_name}.*\"}) > #{startup_alert_threshold_seconds}) "\ - "and on(pod) (rate(prober_probe_total{probe_type=\"Readiness\",result=\"failed\",pod=~\"^#{k8s_app_resources_name}.*\"}[1m]) > 0))", - 'labels' => { - 'severity' => 'warning', - 'alertname' => "#{k8s_app_resources_name} failed readiness probe when deployment not in progress", - 'alert_owner_channel' => alerts_channel - }, - 'annotations' => { - 'message' => '{{ $labels.namespace }}/{{ $labels.pod }} has failed readiness probe when deployment not in progress', - 'status_page_url' => "https://go.timgroup.com/insight/#{site}/proxy/#{@environment.name}/{{ $labels.pod }}/info/status" - } - } - end - { - 'apiVersion' => 'monitoring.coreos.com/v1', - 'kind' => 'PrometheusRule', - 'metadata' => { - 'labels' => { - 'prometheus' => 'main', - 'role' => 'alert-rules' - }.merge(app_service_labels), - 'name' => k8s_app_resources_name, - 'namespace' => @environment.name - }, - 'spec' => { - 'groups' => [ - { - 'name' => 'stacks-alerts', - 'rules' => rules - } - ] - } - } - end - - def scale_memory(memory, coeff) - m = memory.match(/^(\d+)(G|M|K)i?$/) - byte_conversion_factor = case m.captures[1].upcase - when 'G' - 1024**3 - when 'M' - 1024**2 - when 'K' - 1024 - end - bytes = (1 + coeff) * m.captures[0].to_i * byte_conversion_factor - "#{(bytes / 1024).floor}K" - end - - def generate_k8s_network_policies(dns_resolver, site, standard_labels) - # this method only does the network policies for the app pods - network_policies = [] - - network_policies += generate_k8s_network_policies_for_dependants(dns_resolver, site, standard_labels) - network_policies += generate_k8s_network_policies_for_dependencies(dns_resolver, site, standard_labels) - - nexus_filters = [{ - 'to' => [{ 'ipBlock' => { 'cidr' => "#{dns_resolver.lookup('office-nexus-001.mgmt.lon.net.local')}/32" } }], - 'ports' => [{ - 'protocol' => 'TCP', - 'port' => 8080 - }] - }] - ingress_match_labels = { - 'machineset' => standard_labels['machineset'], - 'group' => standard_labels['group'], - 'app.kubernetes.io/component' => 'app_service' + 'limits' => { + 'memory' => scale_memory(@jvm_heap, @headspace) + }.merge(ephemeral_storage_limit).merge(cpu_limit), + 'requests' => { + 'memory' => scale_memory(@jvm_heap, @headspace) + }.merge(ephemeral_storage_limit).merge(cpu_request) } - network_policies << create_egress_network_policy('off-nexus', @environment.name, standard_labels, - nexus_filters, ingress_match_labels) - - prom_filters = [generate_pod_and_namespace_selector_filter('monitoring', 'prometheus' => 'main')] - network_policies << create_ingress_network_policy_for_internal_service('mon', 'prom-main', - @environment.name, standard_labels, - prom_filters) - - network_policies end - def generate_k8s_service_account(dns_resolver, site, standard_labels) - if enable_service_account - - network_policy_spec = { - 'podSelector' => { - 'matchLabels' => { - 'machineset' => standard_labels['machineset'], - 'group' => standard_labels['group'], - 'app.kubernetes.io/component' => 'app_service' - } - }, - 'policyTypes' => [ - 'Egress' - ], - - 'egress' => [{ - 'to' => [{ - 'ipBlock' => { - 'cidr' => "#{dns_resolver.lookup("#{site}-kube-apiserver-vip.mgmt.#{site}.net.local")}/32" + def create_init_containers_snippet(secrets, app_name, app_version) + [{ + 'image' => 'repo.net.local:8080/timgroup/config-generator:1.0.5', + 'name' => 'config-generator', + 'env' => secrets.map do |_hiera_key, secret_name| + { + 'name' => "SECRET_#{secret_name}", + 'valueFrom' => { + 'secretKeyRef' => { + 'name' => k8s_app_resources_name, + 'key' => secret_name } - }], - 'ports' => [{ - 'protocol' => 'TCP', - 'port' => 6443 - }] - }] - } - - hash = Support::DigestGenerator.from_hash(network_policy_spec) - - [{ - 'apiVersion' => 'v1', - 'kind' => 'ServiceAccount', - 'metadata' => { - 'namespace' => @environment.name, - 'name' => k8s_app_resources_name, - 'labels' => standard_labels - } - }, { - 'apiVersion' => 'networking.k8s.io/v1', - 'kind' => 'NetworkPolicy', - 'metadata' => { - 'name' => "allow-out-to-#{site}-kubernetes-api-#{hash}", - 'namespace' => @environment.name, - 'labels' => standard_labels - }, - 'spec' => network_policy_spec - }] - else - [] - end - end - - def create_ingress_network_policy_for_external_service(virtual_service_env, virtual_service_name, env_name, labels, filters) - spec = { - 'podSelector' => { - 'matchLabels' => { - 'machineset' => labels['machineset'], - 'group' => labels['group'], - 'app.kubernetes.io/component' => 'ingress' - } - }, - 'policyTypes' => [ - 'Ingress' - ], - 'ingress' => [{ - 'from' => filters, - 'ports' => [{ - 'protocol' => 'TCP', - 'port' => 'http' - }] - }] - } - - hash = Support::DigestGenerator.from_hash(spec) - - { - 'apiVersion' => 'networking.k8s.io/v1', - 'kind' => 'NetworkPolicy', - 'metadata' => { - 'name' => "allow-in-from-#{virtual_service_env}-#{virtual_service_name}-#{hash}", - 'namespace' => env_name, - 'labels' => labels - }, - 'spec' => spec - } - end - - def create_ingress_network_policy_for_internal_service(virtual_service_env, virtual_service_name, env_name, labels, filters) - spec = { - 'podSelector' => { - 'matchLabels' => { - 'machineset' => labels['machineset'], - 'group' => labels['group'], - 'app.kubernetes.io/component' => 'app_service' - } - }, - 'policyTypes' => [ - 'Ingress' - ], - 'ingress' => [{ - 'from' => filters, - 'ports' => [{ - 'protocol' => 'TCP', - 'port' => 'app' - }] - }] - } - - hash = Support::DigestGenerator.from_hash(spec) - - { - 'apiVersion' => 'networking.k8s.io/v1', - 'kind' => 'NetworkPolicy', - 'metadata' => { - 'name' => "allow-in-from-#{virtual_service_env}-#{virtual_service_name}-#{hash}", - 'namespace' => env_name, - 'labels' => labels - }, - 'spec' => spec - } - end - - def create_ingress_network_policy_to_ingress_for_internal_service(virtual_service_env, virtual_service_name, - env_name, labels, port, filters) - spec = { - 'podSelector' => { - 'matchLabels' => { - 'machineset' => labels['machineset'], - 'group' => labels['group'], - 'app.kubernetes.io/component' => 'ingress' - } - }, - 'policyTypes' => [ - 'Ingress' - ], - 'ingress' => [{ - 'from' => filters, - 'ports' => [{ - 'protocol' => 'TCP', - 'port' => port - }] - }] - } - - hash = Support::DigestGenerator.from_hash(spec) - - { - 'apiVersion' => 'networking.k8s.io/v1', - 'kind' => 'NetworkPolicy', - 'metadata' => { - 'name' => "allow-in-from-#{virtual_service_env}-#{virtual_service_name}-#{hash}", - 'namespace' => env_name, - 'labels' => labels - }, - 'spec' => spec - } - end - - def create_egress_network_policy(name, env_name, labels, egresses, pod_selector_match_labels) - spec = { - 'podSelector' => { - 'matchLabels' => pod_selector_match_labels - }, - 'policyTypes' => [ - 'Egress' - ], - 'egress' => egresses - } - - hash = Support::DigestGenerator.from_hash(spec) - - { - 'apiVersion' => 'networking.k8s.io/v1', - 'kind' => 'NetworkPolicy', - 'metadata' => { - 'name' => "allow-out-to-#{name}-#{hash}", - 'namespace' => env_name, - 'labels' => labels - }, - 'spec' => spec - } - end - - def create_egress_network_policy_for_external_service(service_name, env_name, labels, egresses, pod_selector_match_labels) - spec = { - 'podSelector' => { - 'matchLabels' => pod_selector_match_labels - }, - 'policyTypes' => [ - 'Egress' - ], - 'egress' => egresses - } - - hash = Support::DigestGenerator.from_hash(spec) - - { - 'apiVersion' => 'networking.k8s.io/v1', - 'kind' => 'NetworkPolicy', - 'metadata' => { - 'name' => "allow-out-to-#{service_name}-#{hash}", - 'namespace' => env_name, - 'labels' => labels - }, - 'spec' => spec - } - end - - def generate_k8s_ingress(name, labels) - { - 'apiVersion' => 'networking.k8s.io/v1beta1', - 'kind' => 'Ingress', - 'metadata' => { - 'name' => name, - 'namespace' => @environment.name, - 'labels' => labels, - 'annotations' => { - 'kubernetes.io/ingress.class' => "traefik-#{labels['machineset']}-#{labels['group']}" - } - }, - 'spec' => { - 'rules' => [{ - 'http' => { - 'paths' => [{ - 'path' => '/', - 'backend' => { - 'serviceName' => name, - 'servicePort' => 80 - } - }] } - }] - } - } - end - - def generate_k8s_ingress_controller_role(name, ingress_labels) - { - 'kind' => 'Role', - 'apiVersion' => 'rbac.authorization.k8s.io/v1', - 'metadata' => { - 'name' => name, - 'namespace' => @environment.name, - 'labels' => ingress_labels - }, - 'rules' => [ + } + end.push( { - 'apiGroups' => [ - "" - ], - 'resources' => %w(secrets services endpoints), - 'verbs' => %w(get list watch) + 'name' => 'CONTAINER_IMAGE', + 'value' => container_image(app_name, app_version) }, { - "apiGroups" => [ - "extensions", - "networking.k8s.io" - ], - "resources" => [ - "ingresses" - ], - "verbs" => %w(get list watch) + 'name' => 'APP_JVM_ARGS', + 'value' => "#{@jvm_args} -Xms#{@jvm_heap} -Xmx#{@jvm_heap}" }, { - "apiGroups" => [ - "extensions", - "networking.k8s.io" - ], - "resources" => [ - "ingresses/status" - ], - "verbs" => [ - "update" - ] + 'name' => 'BASE_JVM_ARGS', + 'value' => "-Djava.awt.headless=true -Dfile.encoding=UTF-8 -XX:ErrorFile=/var/log/app/error.log " \ + "-XX:HeapDumpPath=/var/log/app -XX:+HeapDumpOnOutOfMemoryError -Djava.security.egd=file:/dev/./urandom " \ + "-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=5000 -Dcom.sun.management.jmxremote.authenticate=false " \ + "-Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.local.only=false " \ + "-Dcom.sun.management.jmxremote.rmi.port=5000 -Djava.rmi.server.hostname=127.0.0.1 " \ + "-Dcom.timgroup.infra.platform=k8s" }, { - "apiGroups" => [ - "traefik.containo.us" - ], - "resources" => %w(middlewares ingressroutes traefikservices ingressroutetcps ingressrouteudps tlsoptions tlsstores), - "verbs" => %w(get list watch) - } - ] - } - end - - def generate_k8s_ingress_controller_network_policies(_name, ingress_labels, dns_resolver, site, masters) - network_policies = [] - - app_service_match_labels = { - 'machineset' => ingress_labels['machineset'], - 'group' => 'blue', - 'app.kubernetes.io/component' => 'app_service' - } - egresses = [{ - 'to' => [ - generate_pod_and_namespace_selector_filter(@environment.name, app_service_match_labels) - ], - 'ports' => [{ - 'protocol' => 'TCP', - 'port' => 'app' - }] - }] - ingress_match_labels = { - 'machineset' => ingress_labels['machineset'], - 'group' => 'blue', - 'app.kubernetes.io/component' => 'ingress' - } - network_policies << create_egress_network_policy("#{@environment.short_name}-#{short_name}", @environment.name, - ingress_labels, egresses, ingress_match_labels) - - api_server_egresses = [{ - 'to' => masters.map do |master| - { - 'ipBlock' => { - 'cidr' => "#{dns_resolver.lookup(master)}/32" - } - } - end, - 'ports' => [{ - 'port' => 6443, - 'protocol' => 'TCP' - }] - }] - - network_policies << create_egress_network_policy_for_external_service('api-server', @environment.name, ingress_labels, - api_server_egresses, ingress_match_labels) - - dependants.reject { |dep| dep.from.kubernetes }.each do |dep| - vs = dep.from - is_same_site = dep.requirement == :same_site - next if is_same_site && !vs.exists_in_site?(vs.environment, site) - - filters = [] - dependant_vms = vs.children.select { |vm| vm.site == (is_same_site ? site : @environment.primary_site) }.sort_by(&:prod_fqdn) - - dependant_vms.each do |vm| - filters << { - 'ipBlock' => { - 'cidr' => "#{dns_resolver.lookup(vm.qualified_hostname(@environment.primary_network))}/32" - } - } - end - network_policies << create_ingress_network_policy_for_external_service(vs.environment.short_name, vs.short_name, - @environment.name, ingress_labels, filters) - end - - prom_filters = [generate_pod_and_namespace_selector_filter('monitoring', 'prometheus' => 'main')] - network_policies << create_ingress_network_policy_to_ingress_for_internal_service('mon', 'prom-main', - @environment.name, ingress_labels, - 'traefik', prom_filters) - - network_policies - end - - def generate_k8s_ingress_controller_service(name, ingress_labels, dns_resolver, site) - { - 'apiVersion' => 'v1', - 'kind' => 'Service', - 'metadata' => { - 'labels' => ingress_labels, - 'name' => name, - 'namespace' => @environment.name, - 'annotations' => { - 'metallb.universe.tf/address-pool' => 'prod-static' - } - }, - 'spec' => { - 'type' => 'LoadBalancer', - 'loadBalancerIP' => dns_resolver.lookup(prod_fqdn(site)).to_s, - 'externalTrafficPolicy' => 'Local', - 'selector' => { - 'machineset' => ingress_labels['machineset'], - 'group' => ingress_labels['group'], - 'app.kubernetes.io/component' => 'ingress' - }, - 'ports' => [ - { - 'name' => 'http', - 'port' => 80, - 'protocol' => 'TCP', - 'targetPort' => 'http' - } - ] - } - } - end - - def generate_k8s_ingress_controller_monitoring_service(name, ingress_labels) - { - 'apiVersion' => 'v1', - 'kind' => 'Service', - 'metadata' => { - 'labels' => ingress_labels.merge('app.kubernetes.io/component' => 'ingress-monitoring'), - 'name' => "#{name}-mon", - 'namespace' => @environment.name - }, - 'spec' => { - 'clusterIP' => 'None', - 'selector' => { - 'machineset' => ingress_labels['machineset'], - 'group' => ingress_labels['group'], - 'app.kubernetes.io/component' => 'ingress' + 'name' => 'GC_JVM_ARGS_JAVA_8', + 'value' => "-XX:+PrintGC -XX:+PrintGCTimeStamps -XX:+PrintGCDateStamps -XX:+PrintGCDetails \ +-Xloggc:/var/log/app/gc.log -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=25M \ +-XX:+PrintGCApplicationStoppedTime" }, - 'ports' => [ - { - 'name' => 'traefik', - 'port' => 10254, - 'protocol' => 'TCP', - 'targetPort' => 'traefik' - } - ] - } - } - end - - def generate_k8s_ingress_controller_deployment(name, ingress_labels) - ingress_controller_labels = ingress_labels.merge('app.kubernetes.io/name' => 'traefik', - 'application' => 'traefik', - 'app.kubernetes.io/version' => '2.2') - - { - 'apiVersion' => 'apps/v1', - 'kind' => 'Deployment', - 'metadata' => { - 'name' => name, - 'namespace' => @environment.name, - 'labels' => ingress_controller_labels - }, - 'spec' => { - 'replicas' => 2, - 'selector' => { - 'matchLabels' => { - 'machineset' => ingress_labels['machineset'], - 'group' => ingress_labels['group'], - 'app.kubernetes.io/component' => ingress_labels['app.kubernetes.io/component'] - } + 'name' => 'GC_JVM_ARGS_JAVA_11', + 'value' => '-Xlog:gc*,safepoint:/var/log/app/gc.log:time,uptime,level,tags:filecount=10,filesize=26214400' + ), + 'volumeMounts' => [ + { + 'name' => 'config-volume', + 'mountPath' => '/config' }, - 'template' => { - 'metadata' => { - 'labels' => ingress_controller_labels - }, - 'spec' => { - 'containers' => [ - { - 'args' => [ - "--accesslog", - "--ping", - "--api.insecure", - "--api.dashboard", - "--entrypoints.http.Address=:8000", - "--entrypoints.http.forwardedHeaders.trustedIPs=127.0.0.1/32,10.0.0.0/8", - "--entrypoints.traefik.Address=:10254", - "--providers.kubernetesingress", - "--providers.kubernetesingress.ingressclass=traefik-#{ingress_labels['machineset']}-#{ingress_labels['group']}", - "--providers.kubernetesingress.ingressendpoint.publishedservice=#{@environment.name}/#{name}", - "--providers.kubernetesingress.namespaces=#{@environment.name}", - "--metrics.prometheus", - "--log.level=DEBUG" - ], - 'image' => 'traefik:v2.2', - 'imagePullPolicy' => 'IfNotPresent', - 'livenessProbe' => { - 'failureThreshold' => 3, - 'httpGet' => { - 'path' => '/ping', - 'port' => 'traefik', - 'scheme' => 'HTTP' - }, - 'initialDelaySeconds' => 10, - 'periodSeconds' => 10, - 'successThreshold' => 1, - 'timeoutSeconds' => 10 - }, - 'name' => 'traefik-ingress-controller', - 'ports' => [ - { - 'containerPort' => 8000, - 'name' => 'http', - 'protocol' => 'TCP' - }, - { - 'containerPort' => 10254, - 'name' => 'traefik', - 'protocol' => 'TCP' - } - ], - 'readinessProbe' => { - 'failureThreshold' => 3, - 'httpGet' => { - 'path' => '/ping', - 'port' => 'traefik', - 'scheme' => 'HTTP' - }, - 'periodSeconds' => 10, - 'successThreshold' => 1, - 'timeoutSeconds' => 10 - }, - 'resources' => { - 'limits' => { - 'cpu' => '300m', - 'memory' => '64Mi' - }, - 'requests' => { - 'cpu' => '200m', - 'memory' => '48Mi' - } - }, - 'terminationMessagePath' => '/dev/termination-log', - 'terminationMessagePolicy' => 'File' - } - ], - 'serviceAccountName' => name, - 'terminationGracePeriodSeconds' => 60 - } - } - } - } - end - - def generate_k8s_ingress_pod_disruption_budget(name, ingress_labels) - { - 'apiVersion' => 'policy/v1beta1', - 'kind' => 'PodDisruptionBudget', - 'metadata' => { - 'name' => name, - 'namespace' => @environment.name, - 'labels' => ingress_labels - }, - 'spec' => { - 'maxUnavailable' => 1, - 'selector' => { - 'matchLabels' => { - 'machineset' => ingress_labels['machineset'], - 'group' => ingress_labels['group'], - 'app.kubernetes.io/component' => ingress_labels['app.kubernetes.io/component'] - } - } - } - } - end - - def generate_k8s_ingress_controller_service_account(name, ingress_labels) - { - 'kind' => 'ServiceAccount', - 'apiVersion' => 'v1', - 'metadata' => { - 'name' => name, - 'namespace' => @environment.name, - 'labels' => ingress_labels - } - } - end - - def generate_k8s_ingress_controller_role_binding(name, ingress_labels) - { - 'kind' => 'RoleBinding', - 'apiVersion' => 'rbac.authorization.k8s.io/v1', - 'metadata' => { - 'name' => name, - 'namespace' => @environment.name, - 'labels' => ingress_labels - }, - 'roleRef' => { - 'apiGroup' => 'rbac.authorization.k8s.io', - 'kind' => 'Role', - 'name' => name - }, - 'subjects' => [{ - 'kind' => 'ServiceAccount', - 'name' => name - }] - } - end - - def generate_k8s_ingress_resources(dns_resolver, hiera_provider, hiera_scope, site, standard_labels, app_service_labels) - masters = hiera_provider.lookup(hiera_scope, "kubernetes/masters/#{site}", []) - - output = [] - - if non_k8s_dependencies_exist? - ingress_labels = standard_labels.merge('app.kubernetes.io/component' => 'ingress') - - k8s_ingress_resources_name = "#{standard_labels['machineset']}-#{standard_labels['group']}-ing" - - output << generate_k8s_ingress(k8s_app_resources_name, app_service_labels) - output << generate_k8s_ingress_controller_service_account(k8s_ingress_resources_name, ingress_labels) - output << generate_k8s_ingress_controller_role(k8s_ingress_resources_name, ingress_labels) - output << generate_k8s_ingress_controller_role_binding(k8s_ingress_resources_name, ingress_labels) - output += generate_k8s_ingress_controller_network_policies(k8s_ingress_resources_name, ingress_labels, dns_resolver, site, masters) - output << generate_k8s_ingress_controller_service(k8s_ingress_resources_name, ingress_labels, dns_resolver, site) - output << generate_k8s_ingress_controller_monitoring_service(k8s_ingress_resources_name, ingress_labels) - output << generate_k8s_ingress_controller_deployment(k8s_ingress_resources_name, ingress_labels) - output << generate_k8s_ingress_pod_disruption_budget(k8s_ingress_resources_name, ingress_labels) - end - output - end - - def generate_pod_and_namespace_selector_filter(namespace, match_labels) - { - 'podSelector' => { - 'matchLabels' => match_labels - }, - 'namespaceSelector' => { - 'matchLabels' => { - 'name' => namespace - } - } - } - end - - def generate_k8s_network_policies_for_dependants(_dns_resolver, site, standard_labels) - important_dependants = [] - network_policies = [] - - if non_k8s_dependencies_exist? - ingress_selector = { - 'machineset' => name, - 'group' => @groups.first, - 'app.kubernetes.io/component' => 'ingress' - } - ingress_filters = [generate_pod_and_namespace_selector_filter(@environment.name, ingress_selector)] - network_policies << create_ingress_network_policy_for_internal_service(@environment.short_name, "#{name}-#{@groups.first}-ing", - @environment.name, standard_labels, - ingress_filters) - - important_dependants = dependants.select { |dep| dep.from.kubernetes } - else - important_dependants = dependants - end - - important_dependants.each do |dep| - vs = dep.from - is_same_site = dep.requirement == :same_site - next if is_same_site && !vs.exists_in_site?(vs.environment, site) - - match_labels = { - 'machineset' => vs.name, - 'group' => vs.groups.first, - 'app.kubernetes.io/component' => 'app_service' - } - filters = [generate_pod_and_namespace_selector_filter(vs.environment.name, match_labels)] - network_policies << create_ingress_network_policy_for_internal_service(vs.environment.short_name, vs.short_name, - @environment.name, standard_labels, filters) - end - - network_policies - end - - def generate_k8s_network_policies_for_dependencies(dns_resolver, site, standard_labels) - network_policies = [] - dependencies.each do |dep| - next if dep.is_a?(Stacks::Dependencies::EnvironmentDependency) - - case dep.to_selector - when Stacks::Dependencies::ServiceSelector - dep.resolve_targets(@environment).each do |vs| - network_policies << create_egress_to_specific_service(vs, dns_resolver, site, standard_labels) - end - when Stacks::Dependencies::AllKubernetesSelector - network_policies << create_egress_network_policy('all', @environment.name, standard_labels, - [ - { - 'to' => [{ - 'podSelector' => { - 'matchLabels' => { - 'app.kubernetes.io/component' => 'app_service' - } - }, - 'namespaceSelector' => { - 'matchLabels' => { - 'isStacksEnvironment' => 'true' - } - } - }], - 'ports' => [{ - 'protocol' => 'TCP', - 'port' => 'app' - }] - }], - 'machineset' => standard_labels['machineset'], - 'group' => standard_labels['group'], - 'app.kubernetes.io/component' => 'app_service') - end - end - network_policies - end - - def create_egress_to_specific_service(vs, dns_resolver, site, standard_labels) - fail "Dependency '#{vs.name}' is not supported for k8s - endpoints method is not implemented" if !vs.respond_to?(:endpoints) - - chosen_site_of_vs = vs.exists_in_site?(vs.environment, site) ? site : vs.environment.primary_site - endpoints = vs.endpoints(self, chosen_site_of_vs) - - egresses = [] - if vs.kubernetes - match_labels = { - 'machineset' => vs.name, - 'group' => vs.groups.first, - 'app.kubernetes.io/component' => 'app_service' - } - egresses << { - 'to' => [ - generate_pod_and_namespace_selector_filter(vs.environment.name, match_labels) - ], - 'ports' => [{ - 'protocol' => 'TCP', - 'port' => 'app' + { + 'name' => 'config-template', + 'mountPath' => '/input/config.properties', + 'subPath' => 'config.properties' }] - } - else - endpoints.each do |e| - ip_blocks = [] - e[:fqdns].uniq.each do |fqdn| - ip_blocks << { 'ipBlock' => { 'cidr' => "#{dns_resolver.lookup(fqdn)}/32" } } - end - egresses << { - 'to' => ip_blocks, - 'ports' => [{ - 'protocol' => 'TCP', - 'port' => e[:port] - }] - } - end - end - app_service_match_labels = { - 'machineset' => standard_labels['machineset'], - 'group' => standard_labels['group'], - 'app.kubernetes.io/component' => 'app_service' - } - - create_egress_network_policy("#{vs.environment.short_name}-#{vs.short_name}", @environment.name, - standard_labels, egresses, app_service_match_labels) - end - - def non_k8s_dependencies_exist? - dependants.count { |dep| !dep.from.kubernetes } > 0 - end - - def startup_alert_threshold_seconds - fail "You must specify a maximum startup time threshold in a kubernetes app service" if @startup_alert_threshold.nil? - - t = @startup_alert_threshold.match(/^(\d+)(s|m|h)$/) - case t.captures[1].upcase - when 'S' - t.captures[0].to_i - when 'M' - t.captures[0].to_i * 60 - when 'H' - t.captures[0].to_i * 60 * 60 - end + }] end end diff --git a/lib/stackbuilder/stacks/services/base_k8s_app.rb b/lib/stackbuilder/stacks/services/base_k8s_app.rb new file mode 100644 index 00000000..80291f31 --- /dev/null +++ b/lib/stackbuilder/stacks/services/base_k8s_app.rb @@ -0,0 +1,181 @@ +require 'stackbuilder/stacks/kubernetes/namespace' +require 'stackbuilder/stacks/maintainers' +require 'erb' + +module Stacks::Services::BaseK8sApp + include Stacks::Kubernetes::ResourceSetApp + include Stacks::Maintainers + + attr_accessor :ports + attr_accessor :ephemeral_storage_size + attr_accessor :cpu_request + attr_accessor :cpu_limit + attr_accessor :memory_limit + + attr_accessor :command + attr_accessor :args + attr_accessor :capabilities + attr_accessor :readiness + + attr_accessor :appconfig + + attr_accessor :alerts_channel + attr_accessor :startup_alert_threshold + attr_accessor :monitor_tucker + attr_accessor :monitor_readiness_probe + attr_accessor :page_on_critical + + attr_accessor :application + attr_accessor :description + attr_accessor :maintainers + + def self.extended(object) + object.configure + end + + def configure + @ports = {} + @ephemeral_storage_size = nil + @maintainers = [] + @cpu_request = false + @cpu_limit = false + @monitor_readiness_probe = true + @monitor_tucker = false + @page_on_critical = false + @artifact_from_nexus = false + @memory_limit = '64Mi' + @command = nil + @args = nil + @capabilities = nil + @readiness = nil + @appconfig = nil + end + + def to_k8s(app_deployer, dns_resolver, hiera_provider) + assert_k8s_requirements + + instances = if @instances.is_a?(Hash) + @instances + else + { @environment.sites.first => @instances } + end + instances.map do |site, replicas| + app_name = application.downcase + group = @groups.first + + begin + app_version = app_deployer.query_cmdb_for(:application => application, + :environment => @environment.name, + :group => group)[:target_version] + rescue + raise("Version not found in cmdb for application: '#{application}', group: '#{group}' in environment: '#{environment.name}'") + end + + domain = "mgmt.#{environment.domain(site)}" + + hiera_scope = { + 'domain' => domain, + 'hostname' => kubernetes ? identity : children.first.hostname, + 'application' => application, + 'stackname' => @stack.name, + 'logicalenv' => @environment.name, + 'group' => group, + 'site' => site + } + + fake_machine_instance = Struct.new(:index).new(0) + erb_vars = { + 'dependencies' => dependency_config(site, fake_machine_instance), + 'credentials_selector' => hiera_provider.lookup(hiera_scope, 'stacks/application_credentials_selector', nil) + }.merge(hiera_scope) + + standard_labels = { + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => @stack.name, + 'machineset' => name, + 'group' => group, + 'app.kubernetes.io/instance' => group, + 'app.kubernetes.io/part-of' => @short_name + } + + app_service_labels = standard_labels.merge('app.kubernetes.io/component' => 'app_service') + + config, used_secrets = generate_app_config(erb_vars, hiera_provider) + + output = super app_deployer, dns_resolver, hiera_provider, app_service_labels + output += app_generate_resources(app_deployer, dns_resolver, hiera_provider, hiera_scope, app_name, app_version, replicas, used_secrets, site, \ + standard_labels, app_service_labels, k8s_app_resources_name, config) + + Stacks::KubernetesResourceBundle.new(site, @environment.name, app_service_labels, output, used_secrets, hiera_scope, k8s_app_resources_name) + end + end + + def prod_fqdn(fabric) + if respond_to? :vip_fqdn + vip_fqdn(:prod, fabric) + else + children.first.prod_fqdn + end + end + + def endpoints(_dependent_service, fabric) + @ports.keys.map do |port_name| + { + :port => @ports[port_name]['port'], + :fqdns => [prod_fqdn(fabric)] + } + end + end + + private + + # FIXME: base_k8s_app as a default is wrong, it should be the name of the method in custom_services.rb + def assert_k8s_requirements(custom_service_name = 'base_k8s_app') + # FIXME: There must be a better way to get the name of the last module that extended machineset rather than have to pass it in here? + fail("#{custom_service_name} '#{name}' in '#{@environment.name}' doesn't define @ports but is depended on by another service") \ + if @ports.empty? && non_k8s_dependencies_exist? + + fail("#{custom_service_name} '#{name}' in '#{@environment.name}' defines ports named both 'app' and 'http'. This is not possible at the moment " \ + "because in some places 'app' is fudged to be 'http' to avoid changing lots of things in one go.") \ + if @ports.keys.select { |port_name| %w(app http).include? port_name }.uniq.length > 1 + + fail("#{custom_service_name} '#{name}' in '#{@environment.name}' requires maintainers (set self.maintainers)") if @maintainers.empty? + fail("#{custom_service_name} '#{name}' in '#{@environment.name}' requires description (set self.description)") if @description.nil? + fail("#{custom_service_name} '#{name}' in '#{@environment.name}' requires application") if application.nil? + fail("#{custom_service_name} '#{name}' in '#{@environment.name} to_k8s doesn\'t know how to deal with multiple groups yet") if @groups.size > 1 + fail("#{custom_service_name} '#{name}' in '#{@environment.name} to_k8s doesn\'t know how to deal with @enable_secondary_site yet") \ + if @enable_secondary_site + fail "#{custom_service_name} '#{name}' in '#{@environment.name}', you must specify a cpu_request if specifying a cpu_limit" \ + if @cpu_limit && !@cpu_request + end + + def k8s_app_resources_name + group = @groups.first + "#{name}-#{group}-app" + end + + def startup_alert_threshold_seconds + fail "You must specify a maximum startup time threshold in a kubernetes app service" if @startup_alert_threshold.nil? + + t = @startup_alert_threshold.match(/^(\d+)(s|m|h)$/) + case t.captures[1].upcase + when 'S' + t.captures[0].to_i + when 'M' + t.captures[0].to_i * 60 + when 'H' + t.captures[0].to_i * 60 * 60 + end + end + + def generate_app_config(erb_vars, hiera_provider) + template = @pre_appconfig_template.nil? ? '' : @pre_appconfig_template + template += @appconfig if @appconfig + template += @post_appconfig_template.nil? ? '' : @pre_appconfig_template + + erb = ConfigERB.new(template, erb_vars, hiera_provider) + contents = erb.render unless template.empty? + + [contents, erb.used_secrets] + end +end diff --git a/lib/stackbuilder/stacks/services/namespace.rb b/lib/stackbuilder/stacks/services/namespace.rb index d8e577da..beb275dc 100644 --- a/lib/stackbuilder/stacks/services/namespace.rb +++ b/lib/stackbuilder/stacks/services/namespace.rb @@ -1,6 +1,7 @@ module Stacks module Services require 'stackbuilder/stacks/services/traits/namespace' + require 'stackbuilder/stacks/services/base_k8s_app' require 'stackbuilder/stacks/services/app_server' require 'stackbuilder/stacks/services/app_service' require 'stackbuilder/stacks/services/bind_server' diff --git a/lib/stackbuilder/stacks/services/rabbitmq_cluster.rb b/lib/stackbuilder/stacks/services/rabbitmq_cluster.rb index fa90482c..6dbbf9d9 100644 --- a/lib/stackbuilder/stacks/services/rabbitmq_cluster.rb +++ b/lib/stackbuilder/stacks/services/rabbitmq_cluster.rb @@ -11,7 +11,11 @@ def self.extended(object) def configure @downstream_services = [] - @ports = [5672] + @ports = { + 'rabbitmq' => { + 'port' => 5672 + } + } @supported_requirements = :accept_any_requirement_default_all_servers end @@ -31,7 +35,7 @@ def to_loadbalancer_config(location, fabric) { vip_fqdn(:prod, fabric) => { 'type' => 'rabbitmq', - 'ports' => @ports, + 'ports' => @ports.keys.map { |port_name| @ports[port_name]['port'] }, 'realservers' => { 'blue' => realservers } diff --git a/lib/stackbuilder/stacks/services/traits/can_be_natted.rb b/lib/stackbuilder/stacks/services/traits/can_be_natted.rb index a5de34da..f7e15b13 100644 --- a/lib/stackbuilder/stacks/services/traits/can_be_natted.rb +++ b/lib/stackbuilder/stacks/services/traits/can_be_natted.rb @@ -66,9 +66,9 @@ def calculate_nat_rules(type, site, requirements) private def create_rules_for_hosts(hostnames, site, type) - ports.map do |port| + ports.keys.map do |port_name| hostnames.map do |hostname| - nat_config.create_rule(environment, type, hostname, site, port) + nat_config.create_rule(environment, type, hostname, site, ports[port_name]['port']) end end.flatten end diff --git a/lib/stackbuilder/stacks/services/virtual_bind_service.rb b/lib/stackbuilder/stacks/services/virtual_bind_service.rb index cd94802f..64d08f86 100644 --- a/lib/stackbuilder/stacks/services/virtual_bind_service.rb +++ b/lib/stackbuilder/stacks/services/virtual_bind_service.rb @@ -8,7 +8,12 @@ def self.extended(object) end def configure - @ports = [53] + @ports = { + 'app' => { + 'port' => 53, + 'protocol' => 'udp' + } + } add_vip_network :mgmt remove_vip_network :prod @nat_config.udp = true @@ -166,7 +171,7 @@ def to_loadbalancer_config(location, fabric) vip_nets.each do |vip_net| lb_config[vip_fqdn(vip_net, fabric)] = { 'type' => 'bind', - 'ports' => @ports, + 'ports' => @ports.keys.map { |port_name| @ports[port_name]['port'] }, 'realservers' => { 'blue' => realservers(location).map { |server| server.qualified_hostname(vip_net) }.sort }, diff --git a/lib/stackbuilder/stacks/services/virtual_proxy_service.rb b/lib/stackbuilder/stacks/services/virtual_proxy_service.rb index d3c2e0d4..30d70333 100644 --- a/lib/stackbuilder/stacks/services/virtual_proxy_service.rb +++ b/lib/stackbuilder/stacks/services/virtual_proxy_service.rb @@ -14,7 +14,14 @@ def self.extended(object) def configure @proxy_vhosts = [] - @ports = [80, 443] + @ports = { + 'http' => { + 'port' => 80 + }, + 'https' => { + 'port' => 443 + } + } @cert = 'wildcard_timgroup_com_2017' @override_vhost_location = {} @vhost_for_lb_healthcheck_override_hack = nil @@ -69,7 +76,7 @@ def to_loadbalancer_config(location, fabric) 'env' => environment.name, 'app' => 'apache2', 'type' => type, - 'ports' => @ports, + 'ports' => @ports.keys.select { |port_name| %w(http https).include? port_name }.map { |port_name| @ports[port_name]['port'] }, 'realservers' => realservers } diff --git a/lib/stackbuilder/stacks/services/virtual_sftp_service.rb b/lib/stackbuilder/stacks/services/virtual_sftp_service.rb index 338892ca..b995b2e0 100644 --- a/lib/stackbuilder/stacks/services/virtual_sftp_service.rb +++ b/lib/stackbuilder/stacks/services/virtual_sftp_service.rb @@ -10,7 +10,17 @@ def self.extended(object) def configure @downstream_services = [] - @ports = [21, 22, 2222] + @ports = { + 'proftpd' => { + 'port' => 21 + }, + 'ssh' => { + 'port' => 22 + }, + 'proftpd-ssh' => { + 'port' => 2222 + } + } end def to_loadbalancer_config(location, fabric) @@ -29,7 +39,7 @@ def to_loadbalancer_config(location, fabric) { vip_fqdn(:prod, fabric) => { 'type' => 'sftp', - 'ports' => @ports, + 'ports' => @ports.keys.map { |port_name| @ports[port_name]['port'] }, 'realservers' => realservers, 'persistent_ports' => @persistent_ports, 'monitor_warn' => monitor_warn.to_s diff --git a/lib/stackbuilder/stacks/services/vpn_service.rb b/lib/stackbuilder/stacks/services/vpn_service.rb index 59ed9d91..3c741cf9 100644 --- a/lib/stackbuilder/stacks/services/vpn_service.rb +++ b/lib/stackbuilder/stacks/services/vpn_service.rb @@ -4,7 +4,16 @@ def self.extended(object) end def configure - @ports = [500, 4500] + @ports = { + 'isakmp' => { + 'port' => 500, + 'protocol' => 'udp' + }, + 'isakmp-nat-t' => { + 'port' => 4500, + 'protocol' => 'udp' + } + } add_vip_network :mgmt @nat_config.tcp = false @nat_config.udp = true diff --git a/spec/app_service_spec.rb b/spec/app_service_spec.rb index 27c9c331..f146edf0 100644 --- a/spec/app_service_spec.rb +++ b/spec/app_service_spec.rb @@ -229,7 +229,8 @@ def k8s_resource(set, kind) 'ports' => [ { 'containerPort' => 8000, - 'name' => 'app' + 'name' => 'app', + 'protocol' => 'TCP' }, { 'containerPort' => 5000, @@ -237,6 +238,10 @@ def k8s_resource(set, kind) } ], 'volumeMounts' => [ + { + 'name' => 'tmp-volume', + 'mountPath' => '/tmp' + }, { 'name' => 'config-volume', 'mountPath' => '/config', @@ -245,10 +250,6 @@ def k8s_resource(set, kind) { 'name' => 'log-volume', 'mountPath' => '/var/log/app' - }, - { - 'name' => 'tmp-volume', - 'mountPath' => '/tmp' } ], 'readinessProbe' => { @@ -273,6 +274,10 @@ def k8s_resource(set, kind) } }], 'volumes' => [ + { + 'name' => 'tmp-volume', + 'emptyDir' => {} + }, { 'name' => 'config-volume', 'emptyDir' => {} @@ -286,10 +291,6 @@ def k8s_resource(set, kind) { 'name' => 'log-volume', 'emptyDir' => {} - }, - { - 'name' => 'tmp-volume', - 'emptyDir' => {} } ] } @@ -607,15 +608,15 @@ def k8s_resource(set, kind) '--ping', '--api.insecure', '--api.dashboard', + '--metrics.prometheus', + '--log.level=DEBUG', + '--entrypoints.traefik.Address=:10254', '--entrypoints.http.Address=:8000', '--entrypoints.http.forwardedHeaders.trustedIPs=127.0.0.1/32,10.0.0.0/8', - '--entrypoints.traefik.Address=:10254', '--providers.kubernetesingress', '--providers.kubernetesingress.ingressclass=traefik-x-blue', '--providers.kubernetesingress.ingressendpoint.publishedservice=e1/x-blue-ing', - '--providers.kubernetesingress.namespaces=e1', - '--metrics.prometheus', - '--log.level=DEBUG' + '--providers.kubernetesingress.namespaces=e1' ], 'image' => 'traefik:v2.2', 'imagePullPolicy' => 'IfNotPresent', @@ -634,13 +635,13 @@ def k8s_resource(set, kind) 'name' => 'traefik-ingress-controller', 'ports' => [ { - 'containerPort' => 8000, - 'name' => 'http', + 'containerPort' => 10254, + 'name' => 'traefik', 'protocol' => 'TCP' }, { - 'containerPort' => 10254, - 'name' => 'traefik', + 'containerPort' => 8000, + 'name' => 'http', 'protocol' => 'TCP' } ], @@ -2834,9 +2835,9 @@ def k8s_resource(set, kind) factory = eval_stacks do stack "mystack" do app_service 'app1', :kubernetes => { 'e1' => true, 'e2' => false } do - self.maintainers = [person('Testers')] - self.description = 'Testing' - self.alerts_channel = 'test' + self.maintainers = [person('Testers')] if kubernetes + self.description = 'Testing' if kubernetes + self.alerts_channel = 'test' if kubernetes self.application = 'myapp' end @@ -2888,9 +2889,9 @@ def k8s_resource(set, kind) factory = eval_stacks do stack "mystack" do app_service 'app1', :kubernetes => false do - self.maintainers = [person('Testers')] - self.description = 'Testing' - self.alerts_channel = 'test' + self.maintainers = [person('Testers')] if kubernetes + self.description = 'Testing' if kubernetes + self.alerts_channel = 'test' if kubernetes self.application = 'myapp' end diff --git a/spec/base_service_spec.rb b/spec/base_service_spec.rb new file mode 100644 index 00000000..989f06fe --- /dev/null +++ b/spec/base_service_spec.rb @@ -0,0 +1,2674 @@ +require 'stackbuilder/stacks/factory' +require 'test_classes' +require 'spec_helper' + +describe 'kubernetes' do + let(:app_deployer) { TestAppDeployer.new('1.2.3') } + let(:failing_app_deployer) { TestAppDeployer.new(nil) } + let(:dns_resolver) do + MyTestDnsResolver.new('e1-x-vip.space.net.local' => '3.1.4.1', + 'e1-app1-001.space.net.local' => '3.1.4.2', + 'e1-app1-002.space.net.local' => '3.1.4.3', + 'e1-app2-vip.space.net.local' => '3.1.4.4', + 'e1-app1-vip.space.net.local' => '3.1.4.5', + 'e1-nonk8sapp-001.space.net.local' => '3.1.4.14', + 'space-kube-apiserver-vip.mgmt.space.net.local' => '3.1.4.12', + 'space-kvm-001.space.net.local' => '10.30.0.252', + 'space-kvm-005.space.net.local' => '10.30.0.251', + 'space-kvm-010.space.net.local' => '10.30.0.250', + 'e1-ntp-vip.space.net.local' => '10.30.1.234' + ) + end + let(:hiera_provider) do + TestHieraProvider.new( + 'secrety/looking/thing' => 'ENC[GPG,hQIMAyhja+HHo', + 'networking/space/prod/range' => '10.30.0.0/16', + 'kubernetes/masters/space' => ['space-kvm-001.space.net.local', 'space-kvm-005.space.net.local', 'space-kvm-010.space.net.local'] + ) + end + + def network_policies_for(factory, env, stack, service) + machine_sets = factory.inventory.find_environment(env).definitions[stack].k8s_machinesets + machine_set = machine_sets[service] + + machine_set.to_k8s(app_deployer, dns_resolver, hiera_provider).flat_map(&:resources).select do |policy| + policy['kind'] == "NetworkPolicy" + end + end + + def k8s_resource(set, kind) + set.to_k8s(app_deployer, dns_resolver, hiera_provider).flat_map(&:resources).find { |s| s['kind'] == kind } + end + + describe 'base service' do + describe 'to_k8s method' do + let(:factory) do + eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => { 'e1' => true } do + self.application = 'test' + self.startup_alert_threshold = '10s' + self.alerts_channel = 'test' + self.maintainers = [person('Testers')] + self.description = 'Test Description' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + end + let(:set) do + factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + end + it 'generates deployment resources' do + expected_deployment = { + 'apiVersion' => 'apps/v1', + 'kind' => 'Deployment', + "metadata" => { + "name" => "x-blue-app", + "namespace" => "e1", + "labels" => { + "app.kubernetes.io/managed-by" => "stacks", + "stack" => "mystack", + "machineset" => "x", + "group" => "blue", + "app.kubernetes.io/instance" => "blue", + "app.kubernetes.io/part-of" => "x", + "app.kubernetes.io/component" => "app_service", + "application" => "test", + "app.kubernetes.io/name" => "test", + "app.kubernetes.io/version" => "1.2.3" + }, + "annotations" => { + "configmap.reloader.stakater.com/reload" => "x-blue-app", + "secret.reloader.stakater.com/reload" => "x-blue-app", + "maintainers" => "[{\"type\":\"Individual\",\"name\":\"Testers\"}]", + "description" => "Test Description" + } + }, + 'spec' => { + "selector" => { + "matchLabels" => { + "machineset" => "x", + "group" => "blue", + "app.kubernetes.io/component" => "app_service", + "participation" => "enabled" + } + }, + "strategy" => { + "type" => "RollingUpdate", + "rollingUpdate" => { + "maxUnavailable" => 1, + "maxSurge" => 0 + } + }, + "progressDeadlineSeconds" => 10, + "replicas" => 2, + "template" => { + "metadata" => { + "labels" => { + "participation" => "enabled", + "app.kubernetes.io/managed-by" => "stacks", + "stack" => "mystack", + "machineset" => "x", + "group" => "blue", + "app.kubernetes.io/instance" => "blue", + "app.kubernetes.io/part-of" => "x", + "app.kubernetes.io/component" => "app_service", + "application" => "test", + "app.kubernetes.io/name" => "test", + "app.kubernetes.io/version" => "1.2.3" + }, + "annotations" => { + "seccomp.security.alpha.kubernetes.io/pod" => "runtime/default", + "maintainers" => "[{\"type\":\"Individual\",\"name\":\"Testers\"}]", + "description" => "Test Description" + } + }, + "spec" => { + "affinity" => { + "podAntiAffinity" => { + "preferredDuringSchedulingIgnoredDuringExecution" => [{ + "podAffinityTerm" => { + "labelSelector" => { + "matchLabels" => { + "machineset" => "x", + "group" => "blue", + "app.kubernetes.io/component" => "app_service" + } + }, + "topologyKey" => "kubernetes.io/hostname" + }, + "weight" => 100 + }] + } + }, + "automountServiceAccountToken" => false, + "containers" => [{ + "securityContext" => { + "readOnlyRootFilesystem" => true, + "allowPrivilegeEscalation" => false, + "capabilities" => { + "drop" => ["ALL"] + } + }, + "image" => "repo.net.local:8080/timgroup/test:1.2.3", + "name" => "test", + "resources" => { + "limits" => { + "memory" => "65536Ki" + }, + "requests" => { + "memory" => "65536Ki" + } + }, + "ports" => [], + "volumeMounts" => [{ + "name" => "tmp-volume", + "mountPath" => "/tmp" + }] + }], + "volumes" => [{ + "name" => "tmp-volume", + "emptyDir" => {} + }] + } + } + } + } + expect(k8s_resource(set, 'Deployment')).to eql(expected_deployment) + end + + it 'generates PodDisruptionBudget resources' do + expected_pod_disruption_budget = { + 'apiVersion' => 'policy/v1beta1', + 'kind' => 'PodDisruptionBudget', + 'metadata' => { + 'name' => 'x-blue-app', + 'namespace' => 'e1', + 'labels' => { + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'app_service' + } + }, + 'spec' => { + 'maxUnavailable' => 1, + 'selector' => { + 'matchLabels' => { + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'app_service' + } + } + } + } + expect(k8s_resource(set, 'PodDisruptionBudget')).to eql(expected_pod_disruption_budget) + end + + it 'generates resources in a sensible order' do + k8s_resources = set.to_k8s(app_deployer, dns_resolver, hiera_provider).first.resources + k8s_resources.group_by { |r| r['metadata']['labels']['app.kubernetes.io/component'] }.each do |_component, resources| + ordering = {} + resources.each_with_index do |s, index| + ordering[s['kind']] = index + end + if %w(Service Deployment).all? { |k| ordering.key? k } + expect(ordering['Service']).to be < ordering['Deployment'] + end + if %w(ConfigMap Deployment).all? { |k| ordering.key? k } + expect(ordering['ConfigMap']).to be < ordering['Deployment'] + end + end + end + end + + describe 'to_k8s method generation of kubernetes service resources' do + # I'm unsure whther doing this is actually a valid service resource? + it 'generates a service resource with an empty port configuration if @ports is overriden' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => { 'e1' => true } do + self.application = 'test' + self.startup_alert_threshold = '10s' + self.alerts_channel = 'test' + self.maintainers = [person('Testers')] + self.description = 'Test Description' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + expected_service = { + 'apiVersion' => 'v1', + 'kind' => 'Service', + 'metadata' => { + 'name' => 'x-blue-app', + 'namespace' => 'e1', + 'labels' => { + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'app_service' + } + }, + 'spec' => { + 'type' => 'ClusterIP', + 'selector' => { + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'app_service', + 'participation' => 'enabled' + }, + 'ports' => [] + } + } + expect(k8s_resource(set, 'Service')).to eql(expected_service) + end + + it 'generates a service resource with the correct ports when @ports is overridden' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => { 'e1' => true } do + self.application = 'test' + self.startup_alert_threshold = '10s' + self.alerts_channel = 'test' + self.maintainers = [person('Testers')] + self.description = 'Test Description' + self.ports = { + 'ntp' => { + 'port' => 123, + 'service_port' => 123, + 'protocol' => 'udp' + } + } + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + expected_service = { + 'apiVersion' => 'v1', + 'kind' => 'Service', + 'metadata' => { + 'name' => 'x-blue-app', + 'namespace' => 'e1', + 'labels' => { + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'app_service' + } + }, + 'spec' => { + 'type' => 'ClusterIP', + 'selector' => { + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'app_service', + 'participation' => 'enabled' + }, + 'ports' => [ + { "name" => "ntp", "port" => 123, "protocol" => "UDP", "targetPort" => 123 } + ] + } + } + expect(k8s_resource(set, 'Service')).to eql(expected_service) + end + end + + describe 'to_k8s method generation of configmap resources' do + it 'doesn\'t generate a configmap by default' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => { 'e1' => true } do + self.application = 'test' + self.startup_alert_threshold = '10s' + self.alerts_channel = 'test' + self.maintainers = [person('Testers')] + self.description = 'Test Description' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + expect(k8s_resource(set, 'ConfigMap')).to be_nil + end + + it 'puts appconfig into the configmap if one is specified' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => { 'e1' => true } do + self.application = 'test' + self.startup_alert_threshold = '10s' + self.alerts_channel = 'test' + self.maintainers = [person('Testers')] + self.description = 'Test Description' + self.appconfig = "appconfig = test line" + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + expected_configmap = { + "apiVersion" => "v1", + "kind" => "ConfigMap", + "metadata" => { + "name" => "x-blue-app", + "namespace" => "e1", + "labels" => { + "app.kubernetes.io/managed-by" => "stacks", + "stack" => "mystack", "machineset" => "x", + "group" => "blue", + "app.kubernetes.io/instance" => "blue", + "app.kubernetes.io/part-of" => "x", + "app.kubernetes.io/component" => "app_service" + } + }, + "data" => { + "config.properties" => "appconfig = test line" + } + } + expect(k8s_resource(set, 'ConfigMap')).to eql expected_configmap + end + end + + describe 'to_k8s method creates Ingress resources' do + it 'does not create ingress resources when there are no dependencies external to the cluster' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + self.instances = 2 + self.startup_alert_threshold = '1h' + end + end + env "e1", :primary_site => 'space', :secondary_site => 'earth' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + resources = set.to_k8s(app_deployer, dns_resolver, hiera_provider) + ingress_resources = resources.flat_map(&:resources).select { |r| r['metadata']['labels']['app.kubernetes.io/component'] == 'ingress' } + expect(ingress_resources).to be_empty + end + + xit 'creates ingress resources for TCP services' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.ports = { + 'ssh' => { + 'port' => 22, + 'service_port' => 22, + 'protocol' => 'tcp' + } + } + + self.application = 'MyApplication' + self.instances = 2 + self.startup_alert_threshold = '1h' + end + app_service 'nonk8sapp' do + self.instances = 1 + depend_on 'x', 'e1' + end + end + env "e1", :primary_site => 'space', :secondary_site => 'earth' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + + expected_ingress = { + 'apiVersion' => 'traefik.containo.us/v1alpha1', + 'kind' => 'IngressRouteTCP', + 'metadata' => { + 'name' => 'x-blue-app', + 'namespace' => 'e1', + 'labels' => { + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'app_service' + }, + 'annotations' => { + 'kubernetes.io/ingress.class' => 'traefik-x-blue' + } + }, + 'spec' => { + "entryPoints" => ["ssh"], + "routes" => [ + { "services" => [ + { "name" => "x-blue-app", "port" => 22, "kind" => "Service" } + ] } + ] + } + } + + expect(k8s_resource(set, 'IngressRouteTCP')).to eql(expected_ingress) + end + + it 'creates ingress resources for UDP services' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.ports = { + 'ntp' => { + 'port' => 123, + 'service_port' => 123, + 'protocol' => 'udp' + } + } + + self.application = 'MyApplication' + self.instances = 2 + self.startup_alert_threshold = '1h' + end + app_service 'nonk8sapp' do + self.instances = 1 + depend_on 'x', 'e1' + end + end + env "e1", :primary_site => 'space', :secondary_site => 'earth' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + + expected_ingress = { + 'apiVersion' => 'traefik.containo.us/v1alpha1', + 'kind' => 'IngressRouteUDP', + 'metadata' => { + 'name' => 'x-blue-app', + 'namespace' => 'e1', + 'labels' => { + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'app_service' + }, + 'annotations' => { + 'kubernetes.io/ingress.class' => 'traefik-x-blue' + } + }, + 'spec' => { + "entryPoints" => ["ntp"], + "routes" => [ + { "services" => [ + { "name" => "x-blue-app", "port" => 123, "kind" => "Service" } + ] } + ] + } + } + + expect(k8s_resource(set, 'IngressRouteUDP')).to eql(expected_ingress) + end + + it 'creates a deployment resource for ingress controllers' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.ports = { + 'ntp' => { + 'port' => 123, + 'service_port' => 123, + 'protocol' => 'udp' + } + } + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + self.instances = 2 + self.startup_alert_threshold = '1h' + end + app_service 'nonk8sapp' do + self.instances = 1 + depend_on 'x', 'e1' + end + end + env "e1", :primary_site => 'space', :secondary_site => 'earth' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + resources = set.to_k8s(app_deployer, dns_resolver, hiera_provider) + + expected_deployment = { + 'apiVersion' => 'apps/v1', + 'kind' => 'Deployment', + 'metadata' => { + 'name' => 'x-blue-ing', + 'namespace' => 'e1', + 'labels' => { + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'ingress', + 'application' => 'traefik', + 'app.kubernetes.io/name' => 'traefik', + 'app.kubernetes.io/version' => '2.2' + } + }, + 'spec' => { + 'replicas' => 2, + 'selector' => { + 'matchLabels' => { + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'ingress' + } + }, + 'template' => { + 'metadata' => { + 'labels' => { + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'ingress', + 'application' => 'traefik', + 'app.kubernetes.io/name' => 'traefik', + 'app.kubernetes.io/version' => '2.2' + } + }, + 'spec' => { + 'containers' => [ + { + 'args' => [ + '--accesslog', + '--ping', + '--api.insecure', + '--api.dashboard', + '--metrics.prometheus', + '--log.level=DEBUG', + '--entrypoints.traefik.Address=:10254', + '--entrypoints.ntp.Address=:8123', + '--providers.kubernetesCRD', + '--providers.kubernetesCRD.ingressclass=traefik-x-blue', + '--providers.kubernetesCRD.namespaces=e1' + ], + 'image' => 'traefik:v2.2', + 'imagePullPolicy' => 'IfNotPresent', + 'livenessProbe' => { + 'failureThreshold' => 3, + 'httpGet' => { + 'path' => '/ping', + 'port' => 'traefik', + 'scheme' => 'HTTP' + }, + 'initialDelaySeconds' => 10, + 'periodSeconds' => 10, + 'successThreshold' => 1, + 'timeoutSeconds' => 10 + }, + 'name' => 'traefik-ingress-controller', + 'ports' => [ + { + 'containerPort' => 10254, + 'name' => 'traefik', + 'protocol' => 'TCP' + }, + { + 'containerPort' => 8123, + 'name' => 'ntp', + 'protocol' => 'UDP' + } + ], + 'readinessProbe' => { + 'failureThreshold' => 3, + 'httpGet' => { + 'path' => '/ping', + 'port' => 'traefik', + 'scheme' => 'HTTP' + }, + 'periodSeconds' => 10, + 'successThreshold' => 1, + 'timeoutSeconds' => 10 + }, + 'resources' => { + 'limits' => { + 'cpu' => '300m', + 'memory' => '64Mi' + }, + 'requests' => { + 'cpu' => '200m', + 'memory' => '48Mi' + } + }, + 'terminationMessagePath' => '/dev/termination-log', + 'terminationMessagePolicy' => 'File' + } + ], + 'serviceAccountName' => 'x-blue-ing', + 'terminationGracePeriodSeconds' => 60 + } + } + } + } + + expect(resources.flat_map(&:resources).find do |r| + r['kind'] == 'Deployment' && r['metadata']['name'] == 'x-blue-ing' + end).to eql(expected_deployment) + end + + it 'creates a pod disruption budget resource for ingress controllers' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.ports = { 'blah' => { 'port' => 123, 'protocol' => 'udp' } } + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + self.instances = 2 + self.startup_alert_threshold = '1h' + end + app_service 'nonk8sapp' do + self.instances = 1 + depend_on 'x', 'e1' + end + end + env "e1", :primary_site => 'space', :secondary_site => 'earth' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + resources = set.to_k8s(app_deployer, dns_resolver, hiera_provider) + + expected_pod_disruption_budget = { + 'apiVersion' => 'policy/v1beta1', + 'kind' => 'PodDisruptionBudget', + 'metadata' => { + 'name' => 'x-blue-ing', + 'namespace' => 'e1', + 'labels' => { + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'ingress' + } + }, + 'spec' => { + 'maxUnavailable' => 1, + 'selector' => { + 'matchLabels' => { + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'ingress' + } + } + } + } + + expect(resources.flat_map(&:resources).find do |r| + r['kind'] == 'PodDisruptionBudget' && r['metadata']['name'] == 'x-blue-ing' + end).to eql(expected_pod_disruption_budget) + end + + it 'creates a service resource for ingress controllers' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.ports = { + 'ntp' => { + 'port' => 123, + 'service_port' => 123, + 'protocol' => 'udp' + } + } + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + self.instances = 2 + self.startup_alert_threshold = '1h' + end + app_service 'nonk8sapp' do + self.instances = 1 + depend_on 'x', 'e1' + end + end + env "e1", :primary_site => 'space', :secondary_site => 'earth' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + resources = set.to_k8s(app_deployer, dns_resolver, hiera_provider) + + expected_service = { + 'apiVersion' => 'v1', + 'kind' => 'Service', + 'metadata' => { + 'name' => 'x-blue-ing', + 'namespace' => 'e1', + 'labels' => { + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'ingress' + }, + 'annotations' => { + 'metallb.universe.tf/address-pool' => 'prod-static' + } + }, + 'spec' => { + 'externalTrafficPolicy' => 'Local', + 'ports' => [ + { + 'name' => 'ntp', + 'port' => 123, + 'protocol' => 'UDP', + 'targetPort' => 'ntp' + } + ], + 'selector' => { + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'ingress' + }, + 'type' => 'LoadBalancer', + 'loadBalancerIP' => '3.1.4.1' + } + } + + expect(resources.flat_map(&:resources).find do |r| + r['kind'] == 'Service' && r['metadata']['name'] == 'x-blue-ing' + end).to eql(expected_service) + end + + it 'creates a headless service resource for ingress controllers to expose the traefik admin interface to prometheus' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.ports = { 'blah' => { 'port' => 123, 'protocol' => 'udp' } } + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + self.instances = 2 + self.startup_alert_threshold = '1h' + end + app_service 'nonk8sapp' do + self.instances = 1 + depend_on 'x', 'e1' + end + end + env "e1", :primary_site => 'space', :secondary_site => 'earth' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + resources = set.to_k8s(app_deployer, dns_resolver, hiera_provider) + + expected_service = { + 'apiVersion' => 'v1', + 'kind' => 'Service', + 'metadata' => { + 'name' => 'x-blue-ing-mon', + 'namespace' => 'e1', + 'labels' => { + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'ingress-monitoring' + } + }, + 'spec' => { + 'ports' => [ + { + 'name' => 'traefik', + 'port' => 10254, + 'protocol' => 'TCP', + 'targetPort' => 'traefik' + } + ], + 'selector' => { + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'ingress' + }, + 'clusterIP' => 'None' + } + } + + expect(resources.flat_map(&:resources).find do |r| + r['kind'] == 'Service' && r['metadata']['name'] == 'x-blue-ing-mon' + end).to eql(expected_service) + end + + it 'creates a role resource for ingress controllers' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.ports = { 'blah' => { 'port' => 123, 'protocol' => 'udp' } } + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + self.instances = 2 + self.startup_alert_threshold = '1h' + end + app_service 'nonk8sapp' do + self.instances = 1 + depend_on 'x', 'e1' + end + end + env "e1", :primary_site => 'space', :secondary_site => 'earth' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + resources = set.to_k8s(app_deployer, dns_resolver, hiera_provider) + + expected_role = { + 'kind' => 'Role', + 'apiVersion' => 'rbac.authorization.k8s.io/v1', + 'metadata' => { + 'name' => 'x-blue-ing', + 'namespace' => 'e1', + 'labels' => { + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'ingress' + } + }, + 'rules' => [ + { + 'apiGroups' => [ + "" + ], + 'resources' => %w(secrets services endpoints), + 'verbs' => %w(get list watch) + }, + { + "apiGroups" => [ + "extensions", + "networking.k8s.io" + ], + "resources" => [ + "ingresses" + ], + "verbs" => %w(get list watch) + }, + { + "apiGroups" => [ + "extensions", + "networking.k8s.io" + ], + "resources" => [ + "ingresses/status" + ], + "verbs" => [ + "update" + ] + }, + { + "apiGroups" => [ + "traefik.containo.us" + ], + "resources" => %w(middlewares ingressroutes traefikservices ingressroutetcps ingressrouteudps tlsoptions tlsstores), + "verbs" => %w(get list watch) + } + ] + } + + expect(resources.flat_map(&:resources).find do |r| + r['kind'] == 'Role' && r['metadata']['name'] == 'x-blue-ing' + end).to eql(expected_role) + end + + it 'creates a serviceaccount resource for ingress controllers' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.ports = { 'blah' => { 'port' => 123, 'protocol' => 'udp' } } + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + self.instances = 2 + self.startup_alert_threshold = '1h' + end + app_service 'nonk8sapp' do + self.instances = 1 + depend_on 'x', 'e1' + end + end + env "e1", :primary_site => 'space', :secondary_site => 'earth' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + resources = set.to_k8s(app_deployer, dns_resolver, hiera_provider) + + expected_service_account = { + 'kind' => 'ServiceAccount', + 'apiVersion' => 'v1', + 'metadata' => { + 'name' => 'x-blue-ing', + 'namespace' => 'e1', + 'labels' => { + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'ingress' + } + } + } + + expect(resources.flat_map(&:resources).find do |r| + r['kind'] == 'ServiceAccount' && r['metadata']['name'] == 'x-blue-ing' + end).to eql(expected_service_account) + end + + it 'creates a role binding resource for ingress controllers' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.ports = { 'blah' => { 'port' => 123, 'protocol' => 'udp' } } + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + self.instances = 2 + self.startup_alert_threshold = '1h' + end + app_service 'nonk8sapp' do + self.instances = 1 + depend_on 'x', 'e1' + end + end + env "e1", :primary_site => 'space', :secondary_site => 'earth' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + resources = set.to_k8s(app_deployer, dns_resolver, hiera_provider) + + expected_role_binding = { + 'kind' => 'RoleBinding', + 'apiVersion' => 'rbac.authorization.k8s.io/v1', + 'metadata' => { + 'name' => 'x-blue-ing', + 'namespace' => 'e1', + 'labels' => { + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'ingress' + } + }, + 'roleRef' => { + 'apiGroup' => 'rbac.authorization.k8s.io', + 'kind' => 'Role', + 'name' => 'x-blue-ing' + }, + 'subjects' => [{ + 'kind' => 'ServiceAccount', + 'name' => 'x-blue-ing' + }] + } + + expect(resources.flat_map(&:resources).find do |r| + r['kind'] == 'RoleBinding' && r['metadata']['name'] == 'x-blue-ing' + end).to eql(expected_role_binding) + end + + it 'creates network policies allowing ingress controllers to talk out to the api server' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.ports = { 'blah' => { 'port' => 123, 'protocol' => 'udp' } } + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + self.instances = 2 + self.startup_alert_threshold = '1h' + end + app_service 'nonk8sapp' do + self.instances = 1 + depend_on 'x', 'e1' + end + end + env "e1", :primary_site => 'space', :secondary_site => 'earth' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + resources = set.to_k8s(app_deployer, dns_resolver, hiera_provider) + + expected_network_policy = { + 'apiVersion' => 'networking.k8s.io/v1', + 'kind' => 'NetworkPolicy', + 'metadata' => { + 'name' => 'allow-out-to-api-server-65cf5ba', + 'namespace' => 'e1', + 'labels' => { + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'ingress' + } + }, + 'spec' => { + 'egress' => [{ + 'to' => [ + { + 'ipBlock' => { + 'cidr' => '10.30.0.252/32' + } + }, + { + 'ipBlock' => { + 'cidr' => '10.30.0.251/32' + } + }, + { + 'ipBlock' => { + 'cidr' => '10.30.0.250/32' + } + } + ], + 'ports' => [{ + 'port' => 6443, + 'protocol' => 'TCP' + }] + }], + 'podSelector' => { + 'matchLabels' => { + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'ingress' + } + }, + 'policyTypes' => [ + 'Egress' + ] + } + } + + expect(resources.flat_map(&:resources).find do |r| + r['kind'] == 'NetworkPolicy' && r['metadata']['name'] =~ /allow-out-to-api-server-/ + end).to eql(expected_network_policy) + end + + it 'creates network policies allowing prometheus to monitor the ingress controllers' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.ports = { 'blah' => { 'port' => 123, 'protocol' => 'udp' } } + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + self.instances = 2 + self.startup_alert_threshold = '1h' + end + app_service 'nonk8sapp' do + self.instances = 1 + depend_on 'x', 'e1' + end + end + env "e1", :primary_site => 'space', :secondary_site => 'earth' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + resources = set.to_k8s(app_deployer, dns_resolver, hiera_provider) + + expected_network_policy = { + 'apiVersion' => 'networking.k8s.io/v1', + 'kind' => 'NetworkPolicy', + 'metadata' => { + 'name' => 'allow-in-from-mon-prom-main-1f525ea', + 'namespace' => 'e1', + 'labels' => { + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'ingress' + } + }, + 'spec' => { + 'ingress' => [{ + 'from' => [{ + 'namespaceSelector' => { + 'matchLabels' => { + 'name' => 'monitoring' + } + }, + 'podSelector' => { + 'matchLabels' => { + 'prometheus' => 'main' + } + } + }], + 'ports' => [{ + 'port' => 'traefik', + 'protocol' => 'TCP' + }] + }], + 'podSelector' => { + 'matchLabels' => { + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'ingress' + } + }, + 'policyTypes' => [ + 'Ingress' + ] + } + } + + expect(resources.flat_map(&:resources).find do |r| + r['kind'] == 'NetworkPolicy' && r['metadata']['name'] == 'allow-in-from-mon-prom-main-1f525ea' + end).to eql(expected_network_policy) + end + end + + describe 'PrometheusRule' do + it 'doesn\'t create an alert rule for critical status components' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + self.startup_alert_threshold = '1h' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + prometheus_rule = k8s_resource(set, 'PrometheusRule') + + expect(prometheus_rule['apiVersion']).to eql('monitoring.coreos.com/v1') + expect(prometheus_rule['metadata']).to eql('labels' => { + 'prometheus' => 'main', + 'role' => 'alert-rules', + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'app_service' + }, + 'name' => 'x-blue-app', + 'namespace' => 'e1') + + expect(prometheus_rule['spec']['groups'].first['name']).to eql('stacks-alerts') + status_critical_rule = prometheus_rule['spec']['groups'].first['rules'].find do |r| + r['alert'] == 'StatusCritical' + end + expect(status_critical_rule).to be_nil + end + + it 'creates an alert rule for pods stuck in a crash loop' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + self.startup_alert_threshold = '1h' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + prometheus_rule = k8s_resource(set, 'PrometheusRule') + + expect(prometheus_rule['apiVersion']).to eql('monitoring.coreos.com/v1') + expect(prometheus_rule['metadata']).to eql('labels' => { + 'prometheus' => 'main', + 'role' => 'alert-rules', + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'app_service' + }, + 'name' => 'x-blue-app', + 'namespace' => 'e1') + + expect(prometheus_rule['spec']['groups'].first['name']).to eql('stacks-alerts') + rule = prometheus_rule['spec']['groups'].first['rules'].find do |r| + r['alert'] == 'PodCrashLooping' + end + expect(rule).to eql('alert' => 'PodCrashLooping', + 'expr' => "kube_pod_container_status_last_terminated_reason{namespace='e1', pod=~'^x-blue-app.*'} == 1 and " \ + "on(pod, container) rate(kube_pod_container_status_restarts_total[5m]) * 300 > 1", + 'labels' => { + 'severity' => 'critical', + 'alertname' => 'x-blue-app is stuck in a crash loop', + 'alert_owner_channel' => 'test' + }, + 'annotations' => { + 'message' => 'Pod {{ $labels.namespace }}/{{ $labels.pod }} ({{ $labels.container }}) is restarting ' \ + '{{ printf "%.2f" $value }} times / 5 minutes.' + }) + end + + it 'creates an alert rule for pods failing to retrieve their image' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + self.startup_alert_threshold = '1h' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + prometheus_rule = k8s_resource(set, 'PrometheusRule') + + expect(prometheus_rule['apiVersion']).to eql('monitoring.coreos.com/v1') + expect(prometheus_rule['metadata']).to eql('labels' => { + 'prometheus' => 'main', + 'role' => 'alert-rules', + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'app_service' + }, + 'name' => 'x-blue-app', + 'namespace' => 'e1') + + expect(prometheus_rule['spec']['groups'].first['name']).to eql('stacks-alerts') + rule = prometheus_rule['spec']['groups'].first['rules'].find do |r| + r['alert'] == 'ImageRetrievalFailure' + end + expect(rule).to eql('alert' => 'ImageRetrievalFailure', + 'expr' => "kube_pod_container_status_waiting_reason{reason=~'^(ErrImagePull|ImagePullBackOff|InvalidImageName)$', " \ + "namespace='e1', pod=~'^x-blue-app.*'} == 1", + 'labels' => { + 'severity' => 'warning', + 'alertname' => 'x-blue-app is failing to retrieve the requested image', + 'alert_owner_channel' => 'test' + }, + 'annotations' => { + 'message' => 'Pod {{ $labels.namespace }}/{{ $labels.pod }} ({{ $labels.container }}) is failing to retrieve ' \ + 'the requested image.' + }) + end + + it 'creates an alert rule for readiness probe failures occurring post-startup' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + + self.startup_alert_threshold = '1h' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + resources = set.to_k8s(app_deployer, dns_resolver, hiera_provider) + + expect(resources.flat_map(&:resources).find do |r| + r['kind'] == 'PrometheusRule' + end['spec']['groups'].first['rules'].find do |rule| + rule['alert'] == 'FailedReadinessProbe' + end).to eql('alert' => 'FailedReadinessProbe', + 'expr' => '(((time() - kube_pod_start_time{pod=~".*x-blue-app.*"}) > 3600) '\ + 'and on(pod) (rate(prober_probe_total{probe_type="Readiness",result="failed",pod=~"^x-blue-app.*"}[1m]) > 0))', + 'labels' => { + 'severity' => 'warning', + 'alertname' => 'x-blue-app failed readiness probe when deployment not in progress', + 'alert_owner_channel' => 'test' + }, + 'annotations' => { + 'message' => '{{ $labels.namespace }}/{{ $labels.pod }} has failed readiness probe when deployment not in progress', + 'status_page_url' => "https://go.timgroup.com/insight/space/proxy/e1/{{ $labels.pod }}/info/status" + }) + end + + it 'allows turning off the readiness probe failure alert' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + + self.startup_alert_threshold = '1h' + self.monitor_readiness_probe = false + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + resources = set.to_k8s(app_deployer, dns_resolver, hiera_provider) + + expect(resources.flat_map(&:resources).find do |r| + r['kind'] == 'PrometheusRule' + end['spec']['groups'].first['rules'].find do |rule| + rule['alert'] == 'FailedReadinessProbe' + end).to eql(nil) + end + + it 'creates an alert rule for missing replicas in a deployment' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + + self.startup_alert_threshold = '1h' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + resources = set.to_k8s(app_deployer, dns_resolver, hiera_provider) + + expect(resources.flat_map(&:resources).find do |r| + r['kind'] == 'PrometheusRule' + end['spec']['groups'].first['rules'].find do |rule| + rule['alert'] == 'DeploymentReplicasMismatch' + end).to eql('alert' => 'DeploymentReplicasMismatch', + 'expr' => "kube_deployment_spec_replicas{job='kube-state-metrics', namespace='e1', deployment='x-blue-app'} != " \ + "kube_deployment_status_replicas_available{job='kube-state-metrics', namespace='e1', deployment='x-blue-app'}", + 'for' => '1h', + 'labels' => { + 'severity' => 'warning', + 'alertname' => 'x-blue-app is missing replicas', + 'alert_owner_channel' => 'test' + }, + 'annotations' => { + 'message' => 'Deployment {{ $labels.namespace }}/{{ $labels.deployment }} has not ' \ + 'matched the expected number of replicas for longer than the startup_alert_threshold (1h).' + }) + end + + it 'sends component alerts to the specified alerting channel' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.alerts_channel = "testing-alerts" + self.description = 'Testing' + + self.application = 'MyApplication' + self.startup_alert_threshold = '1h' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + status_critical_rule = k8s_resource(set, 'PrometheusRule')['spec']['groups'].first['rules'].find do |r| + r['alert'] == 'DeploymentReplicasMismatch' + end + expect(status_critical_rule['labels']['alert_owner_channel']).to eql('testing-alerts') + end + end + + describe 'instance control' do + it 'controls the number of replicas in the primary site' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + self.instances = 3000 + self.startup_alert_threshold = '1h' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + expect(k8s_resource(set, 'Deployment')['spec']['replicas']).to eql(3000) + end + + it 'controls the number of replicas in the specific sites' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + self.instances = { + 'space' => 2, + 'earth' => 3 + } + self.startup_alert_threshold = '1h' + end + end + env "e1", :primary_site => 'space', :secondary_site => 'earth' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + resources = set.to_k8s(app_deployer, dns_resolver, hiera_provider) + + expect(resources.find { |r| r.site == 'space' }.resources.find { |r| r['kind'] == 'Deployment' }['spec']['replicas']).to eql(2) + expect(resources.find { |r| r.site == 'earth' }.resources.find { |r| r['kind'] == 'Deployment' }['spec']['replicas']).to eql(3) + end + end + + it 'generates config from app-defined template' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + self.appconfig = < +EOL + self.startup_alert_threshold = '1h' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + expect(k8s_resource(set, 'ConfigMap')['data']['config.properties']).to match(/site=space/) + end + + # it 'tracks secrets needed from hiera' do + # factory = eval_stacks do + # stack "mystack" do + # base_service "x", :kubernetes => true do + # self.maintainers = [person('Testers')] + # self.description = 'Testing' + # self.alerts_channel = 'test' + # + # self.application = 'MyApplication' + # self.appconfig = < + # array_secret=<%= secret('my/very/secret.array', 0) %> + # EOL + # self.startup_alert_threshold = '1h' + # end + # end + # env "e1", :primary_site => 'space' do + # instantiate_stack "mystack" + # end + # end + # + # set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + # + # expect(k8s_resource(set, 'ConfigMap')['data']['config.properties']). + # to match(/secret={SECRET:my_very_secret_data.*array_secret={SECRET:my_very_secret_array_0/m) + # + # expect(k8s_resource(set, 'Deployment')['spec']['template']['spec']['initContainers']. + # first['env']. + # find { |e| e['name'] =~ /data/ }). + # to eql( + # 'name' => 'SECRET_my_very_secret_data', + # 'valueFrom' => { + # 'secretKeyRef' => { + # 'name' => 'x-blue-app', + # 'key' => 'my_very_secret_data' + # } + # }) + # + # expect(k8s_resource(set, 'Deployment')['spec']['template']['spec']['initContainers']. + # first['env']. + # find { |e| e['name'] =~ /array/ }). + # to eql( + # 'name' => 'SECRET_my_very_secret_array_0', + # 'valueFrom' => { + # 'secretKeyRef' => { + # 'name' => 'x-blue-app', + # 'key' => 'my_very_secret_array_0' + # } + # }) + # + # k8s = set.to_k8s(app_deployer, dns_resolver, hiera_provider) + # expect(k8s.first.secrets).to eql( + # 'my/very/secret.data' => 'my_very_secret_data', + # 'my/very/secret.array' => 'my_very_secret_array_0') + # end + + it 'blows up when hiera function used for an encrypted value' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + self.startup_alert_threshold = '1h' + + self.application = 'MyApplication' + self.appconfig = < +EOL + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + expect { set.to_k8s(app_deployer, dns_resolver, hiera_provider) }. + to raise_error(/The hiera value for .* is encrypted/) + end + + it 'fails when the app version cannot be found' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + expect { set.to_k8s(failing_app_deployer, dns_resolver, hiera_provider) }. + to raise_error(RuntimeError, /Version not found in cmdb/) + end + + it 'does not mess with lbs for k8s things' do + factory = eval_stacks do + stack "mystack" do + app_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + end + end + stack 'loadbalancer_service' do + loadbalancer_service do + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + instantiate_stack 'loadbalancer_service' + end + end + lb_first_machine_def = factory.inventory.find_environment("e1"). + definitions['loadbalancer_service'].children.first.children.first + expect(lb_first_machine_def.to_enc["role::loadbalancer"]["virtual_servers"].size).to eq(0) + end + + it 'sets up a service account when use_service_account is specified and adds it to the deployment resource' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + self.application = 'MyApplication' + self.startup_alert_threshold = '1h' + + use_service_account + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + pod_spec = k8s_resource(set, 'Deployment')['spec']['template']['spec'] + service_account = k8s_resource(set, 'ServiceAccount') + + expect(pod_spec['automountServiceAccountToken']).to eq(true) + expect(pod_spec['serviceAccountName']).to eq('x-blue-app') + + expect(service_account).to eq( + 'apiVersion' => 'v1', + 'kind' => 'ServiceAccount', + 'metadata' => { + 'namespace' => 'e1', + 'name' => 'x-blue-app', + 'labels' => { + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'app_service' + } + } + ) + end + + it 'creates the correct network polices to allow the pods to talk to the Kubernetes api' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + self.application = 'MyApplication' + self.startup_alert_threshold = '1h' + + use_service_account + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + + network_policies = network_policies_for(factory, 'e1', 'mystack', 'x') + + expect(network_policies.size).to eq(2) + network_policy = network_policies.last + expect(network_policy['metadata']['name']).to eql('allow-out-to-space-kubernetes-api-dcbf68f') + expect(network_policy['metadata']['namespace']).to eql('e1') + expect(network_policy['metadata']['labels']).to eql( + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'mystack', + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'x', + 'app.kubernetes.io/component' => 'app_service' + ) + expect(network_policy['spec']['podSelector']['matchLabels']).to eql( + 'machineset' => 'x', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'app_service' + ) + expect(network_policy['spec']['policyTypes']).to eql(['Egress']) + expect(network_policy['spec']['egress'].size).to eq(1) + expect(network_policy['spec']['egress'].first['to'].size).to eq(1) + expect(network_policy['spec']['egress'].first['ports'].size).to eq(1) + expect(network_policy['spec']['egress'].first['to']).to include('ipBlock' => { 'cidr' => '3.1.4.12/32' }) + expect(network_policy['spec']['egress'].first['ports'].first['protocol']).to eql('TCP') + expect(network_policy['spec']['egress'].first['ports'].first['port']).to eq(6443) + end + + describe 'limits (max) and requests (min)' do + it 'bases container limits and requests on the max heap memory' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'MyApplication' + self.memory_limit = '100G' + self.startup_alert_threshold = '1h' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + app_container = k8s_resource(set, 'Deployment')['spec']['template']['spec']['containers'].first + + expect(app_container['resources']['limits']['memory']).to eq('104857600Ki') + expect(app_container['resources']['requests']['memory']).to eq('104857600Ki') + end + + it 'allows setting a milli cpu limit and request' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + self.application = 'MyApplication' + self.startup_alert_threshold = '1h' + + self.cpu_request = '100m' + self.cpu_limit = '500m' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + resources = k8s_resource(set, 'Deployment')['spec']['template']['spec']['containers'][0]['resources'] + expect(resources['requests']['cpu']).to eq('100m') + expect(resources['limits']['cpu']).to eq('500m') + end + end + + describe 'metadata' do + describe 'maintainers' do + it 'allows maintainers to be people' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.application = 'MyApplication' + self.maintainers = [ + person('Andrew Parker', :slack => '@aparker', :email => 'andy.parker@timgroup.com'), + person('Uncontactable'), + person('Joe Maille', :email => 'joe@example.com')] + self.description = 'testing' + self.alerts_channel = 'test' + self.startup_alert_threshold = '1h' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + annotations = k8s_resource(set, 'Deployment')['metadata']['annotations'] + + expect(JSON.load(annotations['maintainers'])).to eq([ + { 'type' => 'Individual', 'name' => 'Andrew Parker', 'slack' => '@aparker', 'email' => 'andy.parker@timgroup.com' }, + { 'type' => 'Individual', 'name' => 'Uncontactable' }, + { 'type' => 'Individual', 'name' => 'Joe Maille', 'email' => 'joe@example.com' } + ]) + end + + it 'allows maintainers to be slack channels' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.application = 'MyApplication' + self.maintainers = [slack('#technology')] + self.description = 'testing' + self.alerts_channel = 'test' + self.startup_alert_threshold = '1h' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + annotations = k8s_resource(set, 'Deployment')['metadata']['annotations'] + + expect(JSON.load(annotations['maintainers'])).to eq([{ 'type' => 'Group', 'slack_channel' => '#technology' }]) + end + + it 'is required' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.application = 'MyApplication' + self.description = 'testing' + self.alerts_channel = 'test' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + + expect do + factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'].to_k8s(app_deployer, dns_resolver, hiera_provider) + end.to raise_error(/base_k8s_app 'x' in 'e1' requires maintainers \(set self\.maintainers\)/) + end + end + + describe 'description' do + it 'provides a description of the service' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.maintainers = [person('Testers')] + self.application = 'MyApplication' + + self.description = "This application is useful for testing stacks" + self.alerts_channel = 'test' + self.startup_alert_threshold = '1h' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + annotations = k8s_resource(set, 'Deployment')['metadata']['annotations'] + + expect(annotations['description']).to eq("This application is useful for testing stacks") + end + + it 'is required' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => true do + self.application = 'MyApplication' + self.maintainers = [person('Testers')] + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + + expect do + factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'].to_k8s(app_deployer, dns_resolver, hiera_provider) + end.to raise_error(/base_k8s_app 'x' in 'e1' requires description \(set self\.description\)/) + end + end + end + end + + describe 'dependencies' do + it 'only connects dependant instances in the same site, when requested' do + factory = eval_stacks do + stack 'testing' do + base_service 'depends_on_everything', :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + self.instances = { + 'mars' => 1 + } + + self.application = 'application' + self.startup_alert_threshold = '1h' + + depend_on 'just_an_app', 'e1', :same_site + end + base_service 'just_an_app', :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + self.instances = { + 'io' => 1, + 'mars' => 1 + } + + self.application = 'application' + self.startup_alert_threshold = '1h' + end + end + env 'e1', :primary_site => 'io', :secondary_site => 'mars' do + instantiate_stack 'testing' + end + end + + dns = AllocatingDnsResolver.new + + machine_sets = factory.inventory.find_environment('e1').definitions['testing'].k8s_machinesets + depends_on_everything_resources = machine_sets['depends_on_everything'].to_k8s(app_deployer, dns, hiera_provider) + just_an_app_resources = machine_sets['just_an_app'].to_k8s(app_deployer, dns, hiera_provider) + + just_an_app_in_io = just_an_app_resources.find { |r| r.site == 'io' } + just_an_app_in_mars = just_an_app_resources.find { |r| r.site == 'mars' } + + expect(just_an_app_in_io.resources.find do |r| + r['kind'] == 'NetworkPolicy' && r['metadata']['name'].include?('allow-in-from-e1-depends_on_e') + end).to be_nil + expect(just_an_app_in_mars.resources.find do |r| + r['kind'] == 'NetworkPolicy' && r['metadata']['name'].include?('allow-in-from-e1-depends_on_e') + end).not_to be_nil + + expect(depends_on_everything_resources.first.resources.find do |r| + r['kind'] == 'NetworkPolicy' && r['metadata']['name'].include?('allow-out-to-e1-just_an_app') + end).not_to be_nil + end + + it 'can depend on all kubernetes instances in the same site' do + factory = eval_stacks do + stack 'testing' do + app_service 'depends_on_everything', :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + self.instances = { + 'mars' => 1 + } + + self.application = 'application' + self.startup_alert_threshold = '1h' + + depend_on :all, :all, :same_site + end + app_service 'just_an_app', :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + self.instances = { + 'io' => 1, + 'mars' => 1 + } + + self.application = 'just_an_app' + self.startup_alert_threshold = '1h' + end + app_service 'another_app', :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + self.instances = { + 'io' => 1, + 'mars' => 1 + } + + self.application = 'another_app' + self.startup_alert_threshold = '1h' + end + end + env 'e1', :primary_site => 'io', :secondary_site => 'mars' do + instantiate_stack 'testing' + end + end + + dns = AllocatingDnsResolver.new + + machine_sets = factory.inventory.find_environment('e1').definitions['testing'].k8s_machinesets + depends_on_everything_resources = machine_sets['depends_on_everything'].to_k8s(app_deployer, dns, hiera_provider) + just_an_app_resources = machine_sets['just_an_app'].to_k8s(app_deployer, dns, hiera_provider) + + just_an_app_in_io = just_an_app_resources.find { |r| r.site == 'io' } + just_an_app_in_mars = just_an_app_resources.find { |r| r.site == 'mars' } + + expect(just_an_app_in_io.resources.find do |r| + r['kind'] == 'NetworkPolicy' && r['metadata']['name'].include?('allow-in-from-e1-depends_on_e') + end).to be_nil + expect(just_an_app_in_mars.resources.find do |r| + r['kind'] == 'NetworkPolicy' && r['metadata']['name'].include?('allow-in-from-e1-depends_on_e') + end).not_to be_nil + + expect(depends_on_everything_resources.first.resources.find do |r| + r['kind'] == 'NetworkPolicy' && r['metadata']['name'].include?('allow-out-to-all') + end).not_to be_nil + + config = depends_on_everything_resources.first.resources.find { |r| r['kind'] == 'ConfigMap' }['data']['config.properties'] + expect(config).to match(/just_an_app\.url=/) + expect(config).to match(/another_app\.url=/) + end + + it 'only connects dependant vms in the same site, when requested' do + factory = eval_stacks do + stack 'testing' do + app_service 'target', :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + self.instances = { + 'mars' => 1 + } + + self.application = 'application' + self.startup_alert_threshold = '1h' + end + app_service 'source' do + self.instances = { + 'io' => 1, + 'mars' => 1 + } + + self.application = 'application' + depend_on 'target', 'e1', :same_site + end + end + env 'e1', :primary_site => 'io', :secondary_site => 'mars' do + instantiate_stack 'testing' + end + end + + dns = AllocatingDnsResolver.new + + machine_sets = factory.inventory.find_environment('e1').definitions['testing'].k8s_machinesets + depends_on_everything_resources = machine_sets['target'].to_k8s(app_deployer, dns, hiera_provider) + + policy = depends_on_everything_resources.first.resources.find do |r| + r['kind'] == 'NetworkPolicy' && r['metadata']['name'].include?('allow-in-from-e1-source') + end + + expect(policy['spec']['ingress'][0]['from']).to eq([ + { 'ipBlock' => { 'cidr' => dns.lookup('e1-source-001.mars.net.local').to_s + '/32' } } + ]) + end + + it 'should create the correct network policies for a service in kubernetes when another non kubernetes service depends on it' do + factory = eval_stacks do + stack "test_app_servers" do + app_service 'app1' do + depend_on 'app2' + end + + base_service 'app2', :kubernetes => true do + self.ports = { + 'ntp' => { + 'port' => 123, + 'protocol' => 'udp' + } + } + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'app2' + self.startup_alert_threshold = '1h' + end + end + + env "e1", :primary_site => "space" do + instantiate_stack "test_app_servers" + end + end + + machine_sets = factory.inventory.find_environment('e1').definitions['test_app_servers'].k8s_machinesets + app2_machine_set = machine_sets['app2'] + expect(app2_machine_set.dependant_instance_fqdns(:primary_site, [app2_machine_set.environment.primary_network])).to eql([ + "e1-app1-001.space.net.local", + "e1-app1-002.space.net.local" + ]) + + network_policies = app2_machine_set.to_k8s(app_deployer, dns_resolver, hiera_provider). + flat_map(&:resources). + select { |s| s['kind'] == "NetworkPolicy" } + + expect(network_policies.size).to eq(6) + + ingress_controller_ingress_policy = network_policies.find do |r| + r['metadata']['name'].include?('allow-in-from-e1-app1') + end + + expect(ingress_controller_ingress_policy).not_to be_nil + expect(ingress_controller_ingress_policy['metadata']['namespace']).to eql('e1') + expect(ingress_controller_ingress_policy['metadata']['labels']).to eql( + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'test_app_servers', + 'machineset' => 'app2', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'app2', + 'app.kubernetes.io/component' => 'ingress' + ) + expect(ingress_controller_ingress_policy['spec']['podSelector']['matchLabels']).to eql( + 'machineset' => 'app2', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'ingress' + ) + expect(ingress_controller_ingress_policy['spec']['policyTypes']).to eql(['Ingress']) + expect(ingress_controller_ingress_policy['spec']['ingress'].size).to eq(1) + expect(ingress_controller_ingress_policy['spec']['ingress'].first['from'].size).to eq(2) + expect(ingress_controller_ingress_policy['spec']['ingress'].first['ports'].size).to eq(1) + expect(ingress_controller_ingress_policy['spec']['ingress'].first['from']).to include('ipBlock' => { 'cidr' => '3.1.4.2/32' }) + expect(ingress_controller_ingress_policy['spec']['ingress'].first['from']).to include('ipBlock' => { 'cidr' => '3.1.4.3/32' }) + expect(ingress_controller_ingress_policy['spec']['ingress'].first['ports'].first['protocol']).to eql('UDP') + expect(ingress_controller_ingress_policy['spec']['ingress'].first['ports'].first['port']).to eq('ntp') + + ingress_controller_egress_policy = network_policies.find do |r| + r['metadata']['name'].include?('allow-out-to-e1-app2') + end + + expect(ingress_controller_egress_policy).not_to be_nil + expect(ingress_controller_egress_policy['metadata']['namespace']).to eql('e1') + expect(ingress_controller_egress_policy['metadata']['labels']).to eql( + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'test_app_servers', + 'machineset' => 'app2', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'app2', + 'app.kubernetes.io/component' => 'ingress' + ) + expect(ingress_controller_egress_policy['spec']['podSelector']['matchLabels']).to eql( + 'machineset' => 'app2', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'ingress' + ) + expect(ingress_controller_egress_policy['spec']['policyTypes']).to eql(['Egress']) + expect(ingress_controller_egress_policy['spec']['egress'].size).to eq(1) + expect(ingress_controller_egress_policy['spec']['egress'].first['to'].size).to eq(1) + expect(ingress_controller_egress_policy['spec']['egress'].first['ports'].size).to eq(1) + expect(ingress_controller_egress_policy['spec']['egress'].first['to'].first['podSelector']['matchLabels']).to eql( + 'machineset' => 'app2', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'app_service' + ) + expect(ingress_controller_egress_policy['spec']['egress'].first['to'].first['namespaceSelector']['matchLabels']['name']).to eql('e1') + expect(ingress_controller_egress_policy['spec']['egress'].first['ports'].first['protocol']).to eql('UDP') + expect(ingress_controller_egress_policy['spec']['egress'].first['ports'].first['port']).to eq('ntp') + + app_ingress_policy = network_policies.find do |r| + r['metadata']['name'].include?('allow-in-from-e1-app2') + end + + expect(app_ingress_policy).not_to be_nil + expect(app_ingress_policy['metadata']['namespace']).to eql('e1') + expect(app_ingress_policy['metadata']['labels']).to eql( + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'test_app_servers', + 'machineset' => 'app2', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'app2', + 'app.kubernetes.io/component' => 'app_service' + ) + expect(app_ingress_policy['spec']['podSelector']['matchLabels']).to eql( + 'machineset' => 'app2', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'app_service' + ) + expect(app_ingress_policy['spec']['policyTypes']).to eql(['Ingress']) + expect(app_ingress_policy['spec']['ingress'].size).to eq(1) + expect(app_ingress_policy['spec']['ingress'].first['from'].size).to eq(1) + expect(app_ingress_policy['spec']['ingress'].first['ports'].size).to eq(1) + expect(app_ingress_policy['spec']['ingress'].first['from'].first['podSelector']['matchLabels']).to eql( + 'machineset' => 'app2', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'ingress' + ) + expect(app_ingress_policy['spec']['ingress'].first['from'].first['namespaceSelector']['matchLabels']['name']).to eql('e1') + expect(app_ingress_policy['spec']['ingress'].first['ports'].first['protocol']).to eql('UDP') + expect(app_ingress_policy['spec']['ingress'].first['ports'].first['port']).to eq('ntp') + end + + it 'should create the correct egress network policies for a service in kubernetes when that service depends on another non kubernetes service' do + factory = eval_stacks do + stack "test_app_servers" do + app_service 'app1' do + self.application = 'app1' + end + + base_service 'app2', :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'app2' + self.startup_alert_threshold = '1h' + depend_on 'app1' + end + end + + env "e1", :primary_site => "space" do + instantiate_stack "test_app_servers" + end + end + + machine_sets = factory.inventory.find_environment('e1').definitions['test_app_servers'].k8s_machinesets + app2_machine_set = machine_sets['app2'] + + network_policies = app2_machine_set.to_k8s(app_deployer, dns_resolver, hiera_provider). + flat_map(&:resources). + select { |s| s['kind'] == "NetworkPolicy" } + + expect(network_policies.size).to eq(2) + expect(network_policies.first['metadata']['name']).to eql('allow-out-to-e1-app1-23bb767') + expect(network_policies.first['metadata']['namespace']).to eql('e1') + expect(network_policies.first['metadata']['labels']).to eql( + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'test_app_servers', + 'machineset' => 'app2', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'app2', + 'app.kubernetes.io/component' => 'app_service' + ) + expect(network_policies.first['spec']['podSelector']['matchLabels']).to eql( + 'machineset' => 'app2', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'app_service' + ) + expect(network_policies.first['spec']['policyTypes']).to eql(['Egress']) + expect(network_policies.first['spec']['egress'].size).to eq(1) + expect(network_policies.first['spec']['egress'].first['to'].size).to eq(1) + expect(network_policies.first['spec']['egress'].first['ports'].size).to eq(1) + expect(network_policies.first['spec']['egress'].first['to']).to include('ipBlock' => { 'cidr' => '3.1.4.5/32' }) + expect(network_policies.first['spec']['egress'].first['ports'].first['protocol']).to eql('TCP') + expect(network_policies.first['spec']['egress'].first['ports'].first['port']).to eq(8000) + end + + it 'should create the correct network policies for two services in kubernetes in the same environment when one service depends on the other' do + factory = eval_stacks do + stack "test_app_servers" do + base_service 'app1', :kubernetes => true do + self.ports = { + 'ntp' => { + 'port' => 123, + 'protocol' => 'udp' + } + } + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'app1' + self.startup_alert_threshold = '1h' + end + + base_service 'app2', :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'app2' + self.startup_alert_threshold = '1h' + depend_on 'app1' + end + end + + env "e1", :primary_site => "space" do + instantiate_stack "test_app_servers" + end + end + + app1_network_policies = network_policies_for(factory, 'e1', 'test_app_servers', 'app1') + app2_network_policies = network_policies_for(factory, 'e1', 'test_app_servers', 'app2') + + ingress = app1_network_policies.first['spec']['ingress'] + expect(app1_network_policies.size).to eq(2) + expect(app1_network_policies.first['metadata']['name']).to eql('allow-in-from-e1-app2-53f41f2') + expect(app1_network_policies.first['metadata']['namespace']).to eql('e1') + expect(app1_network_policies.first['metadata']['labels']).to eql( + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'test_app_servers', + 'machineset' => 'app1', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'app1', + 'app.kubernetes.io/component' => 'app_service' + ) + expect(app1_network_policies.first['spec']['podSelector']['matchLabels']).to eql( + 'machineset' => 'app1', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'app_service' + ) + expect(app1_network_policies.first['spec']['policyTypes']).to eql(['Ingress']) + expect(ingress.size).to eq(1) + expect(ingress.first['from'].size).to eq(1) + expect(ingress.first['ports'].size).to eq(1) + expect(ingress.first['from'].first['podSelector']['matchLabels']).to eql( + 'machineset' => 'app2', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'app_service' + ) + expect(ingress.first['from'].first['namespaceSelector']['matchLabels']['name']).to eql('e1') + expect(ingress.first['ports'].first['protocol']).to eql('UDP') + expect(ingress.first['ports'].first['port']).to eq('ntp') + + egress = app2_network_policies.first['spec']['egress'] + expect(app2_network_policies.size).to eq(2) + expect(app2_network_policies.first['metadata']['name']).to eql('allow-out-to-e1-app1-ea24b2a') + expect(app2_network_policies.first['metadata']['namespace']).to eql('e1') + expect(app2_network_policies.first['metadata']['labels']).to eql( + 'app.kubernetes.io/managed-by' => 'stacks', + 'stack' => 'test_app_servers', + 'machineset' => 'app2', + 'group' => 'blue', + 'app.kubernetes.io/instance' => 'blue', + 'app.kubernetes.io/part-of' => 'app2', + 'app.kubernetes.io/component' => 'app_service' + ) + expect(app2_network_policies.first['spec']['podSelector']['matchLabels']).to eql( + 'machineset' => 'app2', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'app_service' + ) + expect(app2_network_policies.first['spec']['policyTypes']).to eql(['Egress']) + expect(egress.size).to eq(1) + expect(egress.first['to'].size).to eq(1) + expect(egress.first['ports'].size).to eq(1) + expect(egress.first['to'].first['podSelector']['matchLabels']).to eql( + 'machineset' => 'app1', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'app_service' + ) + expect(egress.first['to'].first['namespaceSelector']['matchLabels']['name']).to eql('e1') + expect(egress.first['ports'].first['protocol']).to eql('TCP') + expect(egress.first['ports'].first['port']).to eq('app') + end + + it 'should not create an egress policy to allow the init container to talk to nexus is @artifact_from_nexus is false' do + factory = eval_stacks do + stack "test_app_servers" do + base_service 'app1', :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'app1' + self.startup_alert_threshold = '1h' + end + end + + env "e1", :primary_site => "space" do + instantiate_stack "test_app_servers" + end + end + + network_policies = network_policies_for(factory, 'e1', 'test_app_servers', 'app1') + + expect(network_policies.size).to eq(1) + expect(network_policies.select do |policy| + policy['metadata']['name'] =~ /allow-out-to-off-nexus-/ + end).to be_empty + end + + it 'should create the correct network policies for two services in \ +kubernetes in different environments in the same site when one service \ +depends on the other' do + factory = eval_stacks do + stack "test_app_server1" do + base_service 'app1', :kubernetes => true do + self.ports = { + 'ntp' => { + 'port' => '123', + 'protocol' => 'udp' + } + } + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'app1' + self.startup_alert_threshold = '1h' + end + end + stack "test_app_server2" do + base_service 'app2', :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'app2' + self.startup_alert_threshold = '1h' + depend_on 'app1', 'e1' + end + end + + env "e1", :primary_site => "space" do + instantiate_stack "test_app_server1" + end + env "e2", :primary_site => "space" do + instantiate_stack "test_app_server2" + end + end + + app1_network_policies = network_policies_for(factory, 'e1', 'test_app_server1', 'app1') + app2_network_policies = network_policies_for(factory, 'e2', 'test_app_server2', 'app2') + + ingress = app1_network_policies.first['spec']['ingress'] + expect(app1_network_policies.size).to eq(2) + expect(app1_network_policies.first['metadata']['name']).to match(/allow-in-from-e2-app2-/) + expect(app1_network_policies.first['metadata']['namespace']).to eql('e1') + expect(app1_network_policies.first['spec']['podSelector']['matchLabels']).to eql( + 'machineset' => 'app1', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'app_service' + ) + expect(app1_network_policies.first['spec']['policyTypes']).to eql(['Ingress']) + expect(ingress.size).to eq(1) + expect(ingress.first['from'].size).to eq(1) + expect(ingress.first['ports'].size).to eq(1) + expect(ingress.first['from'].first['podSelector']['matchLabels']).to eql( + 'machineset' => 'app2', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'app_service' + ) + expect(ingress.first['from'].first['namespaceSelector']['matchLabels']['name']).to eql('e2') + expect(ingress.first['ports'].first['protocol']).to eql('UDP') + expect(ingress.first['ports'].first['port']).to eq('ntp') + + egress = app2_network_policies.first['spec']['egress'] + expect(app2_network_policies.size).to eq(2) + expect(app2_network_policies.first['metadata']['name']).to eql('allow-out-to-e1-app1-ea24b2a') + expect(app2_network_policies.first['metadata']['namespace']).to eql('e2') + expect(app2_network_policies.first['spec']['podSelector']['matchLabels']).to eql( + 'machineset' => 'app2', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'app_service' + ) + expect(app2_network_policies.first['spec']['policyTypes']).to eql(['Egress']) + expect(egress.size).to eq(1) + expect(egress.first['to'].size).to eq(1) + expect(egress.first['ports'].size).to eq(1) + expect(egress.first['to'].first['podSelector']['matchLabels']).to eql( + 'machineset' => 'app1', + 'group' => 'blue', + 'app.kubernetes.io/component' => 'app_service' + ) + expect(egress.first['to'].first['namespaceSelector']['matchLabels']['name']).to eql('e1') + expect(egress.first['ports'].first['protocol']).to eql('TCP') + expect(egress.first['ports'].first['port']).to eq('app') + end + + it 'should fail when dependency does not provide endpoints' do + factory = eval_stacks do + stack "test_app_servers" do + app_service 'app1', :kubernetes => true do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'app' + self.startup_alert_threshold = '1h' + depend_on 'logstash-receiver' + end + logstash_receiver 'logstash-receiver' do + end + end + env "e1", :primary_site => "space" do + instantiate_stack "test_app_servers" + end + end + + machine_sets = factory.inventory.find_environment('e1').definitions['test_app_servers'].k8s_machinesets + machine_set = machine_sets['app1'] + expect { machine_set.to_k8s(app_deployer, dns_resolver, hiera_provider) }.to raise_error( + RuntimeError, + match(/not supported for k8s - endpoints method is not implemented/)) + end + + it 'allows an environment to depend on a service' do + factory = eval_stacks do + stack "test_app_servers" do + base_service 'ntp', :kubernetes => true do + self.ports = { + 'ntp' => { + 'port' => 123, + 'protocol' => 'udp' + } + } + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + + self.application = 'ntp' + self.startup_alert_threshold = '1m' + end + end + env "e1", :primary_site => "space" do + depend_on 'ntp' + instantiate_stack "test_app_servers" + end + end + app1_network_policies = network_policies_for(factory, 'e1', 'test_app_servers', 'ntp') + allow_env_policies = app1_network_policies.select { |policy| policy['metadata']['name'] =~ /allow-in-from-e1-e1-/ } + expect(allow_env_policies.size).to be(1) + allow_env_policy = allow_env_policies.first + pp allow_env_policy + + expect(allow_env_policy['spec']['podSelector']['matchLabels']).to eq("machineset" => "ntp", + "group" => "blue", + "app.kubernetes.io/component" => "ingress") + expect(allow_env_policy['spec']['ingress'].first['from']).to eq [{ "ipBlock" => { "cidr" => "10.30.0.0/16" } }] + expect(allow_env_policy['spec']['ingress'].first['ports']).to eq [{ "protocol" => "UDP", "port" => "ntp" }] + end + end + + it 'raises an error if ports contains both names \'app\' and \'http\'' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => { 'e1' => true } do + self.ports = { + 'app' => { 'port' => 8000 }, + 'http' => { 'port' => 80 } + } + self.application = 'ntp' + self.startup_alert_threshold = '10s' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + # FIXME: Technically the error should be base_service, not base_k8s_app. But see other FIXME's in base_k8s_app.rb + expect do + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + set.to_k8s(app_deployer, dns_resolver, hiera_provider).first.resources + end.to raise_error('base_k8s_app \'x\' in \'e1\' defines ports named both \'app\' and \'http\'. This is not possible at the moment ' \ + 'because in some places \'app\' is fudged to be \'http\' to avoid changing lots of things in one go.') + end + + it 'raises an error if @ports is empty and something else depends on the service' do + factory = eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => { 'e1' => true } do + self.maintainers = [person('Testers')] + self.description = 'Testing' + self.alerts_channel = 'test' + self.application = 'ntp' + self.startup_alert_threshold = '10s' + end + app_service 'nonk8sapp' do + self.instances = 1 + depend_on 'x', 'e1' + end + end + env "e1", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + expect do + set = factory.inventory.find_environment('e1').definitions['mystack'].k8s_machinesets['x'] + set.to_k8s(app_deployer, dns_resolver, hiera_provider).first.resources + end.to raise_error('base_k8s_app \'x\' in \'e1\' doesn\'t define @ports but is depended on by another service') + end +end diff --git a/spec/bind_server_spec.rb b/spec/bind_server_spec.rb index 33b0b68f..b123a562 100644 --- a/spec/bind_server_spec.rb +++ b/spec/bind_server_spec.rb @@ -540,4 +540,54 @@ def find_host(fqdn) expect(host.to_spec[:nameserver]).to eql('4.3.2.2') end end + + describe_stack 'load balancer config for bind services should be correct' do + given do + stack 'lb' do + loadbalancer_service + end + + stack 'nameserver' do + bind_service 'ns' do + each_machine do |machine| + machine.remove_network :prod + end + end + end + + env 'o', :primary_site => 'oy' do + env 'oy' do + instantiate_stack 'nameserver' + instantiate_stack 'lb' + end + end + end + + host('oy-ns-001.mgmt.oy.net.local') do |host| + expect(host.virtual_service.vip_networks).to be_eql [:mgmt] + expect(host.to_enc['role::bind_server']['vip_fqdns']).to eql(['oy-ns-vip.mgmt.oy.net.local']) + expect(host.to_spec[:networks]).to eql([:mgmt]) + expect(host.to_spec[:qualified_hostnames]).to be_eql(:mgmt => 'oy-ns-001.mgmt.oy.net.local') + end + + host('oy-lb-001.mgmt.oy.net.local') do |host| + expect(host.to_enc['role::loadbalancer']['virtual_servers']['oy-ns-vip.mgmt.oy.net.local']['type']).to eq 'bind' + expect(host.to_enc['role::loadbalancer']['virtual_servers']['oy-ns-vip.mgmt.oy.net.local']['ports']).to eq [53] + healthchecks = host.to_enc['role::loadbalancer']['virtual_servers']['oy-ns-vip.mgmt.oy.net.local']['healthchecks'] + expect(healthchecks).to eq( + [{ "healthcheck" => "MISC_CHECK", + "arg_style" => "PARTICIPATION", + "path" => "/opt/youdevise/keepalived/healthchecks/bin/check_participation.rb", + "url_path" => "/participation" }, + { "healthcheck" => "MISC_CHECK", + "arg_style" => "APPEND_HOST", + "path" => "/usr/bin/host -4 -W 3 -t A -s apt.mgmt.oy.net.local" }, + { "healthcheck" => "MISC_CHECK", + "arg_style" => "APPEND_HOST", + "path" => "/usr/bin/host -4 -W 3 -t A -s gw-vip.oy.net.local" }, + { "healthcheck" => "MISC_CHECK", + "arg_style" => "APPEND_HOST", + "path" => "/usr/bin/host -4 -W 3 -t A -s gw-vip.front.oy.net.local" }]) + end + end end diff --git a/spec/cmd_spec.rb b/spec/cmd_spec.rb index adf55dd1..7eba2b6e 100644 --- a/spec/cmd_spec.rb +++ b/spec/cmd_spec.rb @@ -157,6 +157,7 @@ def capture_stdout(&block) '--prune-whitelist', '/v1/ServiceAccount', '--prune-whitelist', 'monitoring.coreos.com/v1/PrometheusRule', '--prune-whitelist', 'policy/v1beta1/PodDisruptionBudget', + '--prune-whitelist', 'traefik.containo.us/v1alpha1/IngressRouteUDP', '-f', '-', :stdin_data => match(/^---\s*$.* @@ -187,6 +188,7 @@ def capture_stdout(&block) '--prune-whitelist', '/v1/ServiceAccount', '--prune-whitelist', 'monitoring.coreos.com/v1/PrometheusRule', '--prune-whitelist', 'policy/v1beta1/PodDisruptionBudget', + '--prune-whitelist', 'traefik.containo.us/v1alpha1/IngressRouteUDP', '-f', '-', :stdin_data => match(/^---\s*$.* @@ -287,6 +289,7 @@ def capture_stdout(&block) '--prune-whitelist', '/v1/ServiceAccount', '--prune-whitelist', 'monitoring.coreos.com/v1/PrometheusRule', '--prune-whitelist', 'policy/v1beta1/PodDisruptionBudget', + '--prune-whitelist', 'traefik.containo.us/v1alpha1/IngressRouteUDP', '-f', '-', :stdin_data => match(/^---\s*$.* @@ -317,6 +320,7 @@ def capture_stdout(&block) '--prune-whitelist', '/v1/ServiceAccount', '--prune-whitelist', 'monitoring.coreos.com/v1/PrometheusRule', '--prune-whitelist', 'policy/v1beta1/PodDisruptionBudget', + '--prune-whitelist', 'traefik.containo.us/v1alpha1/IngressRouteUDP', '-f', '-', :stdin_data => match(/^---\s*$.* @@ -432,6 +436,7 @@ def makes_calls_to_provision(machineset_matcher) '--prune-whitelist', '/v1/ServiceAccount', '--prune-whitelist', 'monitoring.coreos.com/v1/PrometheusRule', '--prune-whitelist', 'policy/v1beta1/PodDisruptionBudget', + '--prune-whitelist', 'traefik.containo.us/v1alpha1/IngressRouteUDP', '-f', '-', :stdin_data => match(/^---\s*$.* @@ -462,6 +467,7 @@ def makes_calls_to_provision(machineset_matcher) '--prune-whitelist', '/v1/ServiceAccount', '--prune-whitelist', 'monitoring.coreos.com/v1/PrometheusRule', '--prune-whitelist', 'policy/v1beta1/PodDisruptionBudget', + '--prune-whitelist', 'traefik.containo.us/v1alpha1/IngressRouteUDP', '-f', '-', :stdin_data => match(/^---\s*$.* @@ -526,6 +532,7 @@ def makes_calls_to_provision(machineset_matcher) '--prune-whitelist', '/v1/ServiceAccount', '--prune-whitelist', 'monitoring.coreos.com/v1/PrometheusRule', '--prune-whitelist', 'policy/v1beta1/PodDisruptionBudget', + '--prune-whitelist', 'traefik.containo.us/v1alpha1/IngressRouteUDP', '-f', '-', :stdin_data => match(/^---\s*$.* @@ -617,6 +624,7 @@ def makes_calls_to_provision(machineset_matcher) '--prune-whitelist', '/v1/ServiceAccount', '--prune-whitelist', 'monitoring.coreos.com/v1/PrometheusRule', '--prune-whitelist', 'policy/v1beta1/PodDisruptionBudget', + '--prune-whitelist', 'traefik.containo.us/v1alpha1/IngressRouteUDP', '-f', '-', :stdin_data => match(/^---\s*$.* @@ -647,6 +655,7 @@ def makes_calls_to_provision(machineset_matcher) '--prune-whitelist', '/v1/ServiceAccount', '--prune-whitelist', 'monitoring.coreos.com/v1/PrometheusRule', '--prune-whitelist', 'policy/v1beta1/PodDisruptionBudget', + '--prune-whitelist', 'traefik.containo.us/v1alpha1/IngressRouteUDP', '-f', '-', :stdin_data => match(/^---\s*$.* diff --git a/spec/custom_services_spec.rb b/spec/custom_services_spec.rb new file mode 100644 index 00000000..b42f2abf --- /dev/null +++ b/spec/custom_services_spec.rb @@ -0,0 +1,23 @@ +require 'stackbuilder/stacks/factory' +require 'test_classes' +require 'spec_helper' + +describe 'kubernetes' do + describe 'custom_services' do + describe 'service_in_kubernetes method' do + it 'will use the calling method name in its fail output' do + expect do + eval_stacks do + stack "mystack" do + base_service "x", :kubernetes => { 'e1' => true } + end + env "e2", :primary_site => 'space' do + instantiate_stack "mystack" + end + end + end.to raise_error 'base_service \'x\' does not specify kubernetes property for environment \'e2\'. ' \ + 'If any environments are specified then all environments where the stack is instantiated must be specified.' + end + end + end +end diff --git a/spec/dependencies_spec.rb b/spec/dependencies_spec.rb index c8ba860f..3d5949b3 100644 --- a/spec/dependencies_spec.rb +++ b/spec/dependencies_spec.rb @@ -349,7 +349,11 @@ app_service 'fundsuserapp' do self.groups = ['blue'] self.application = 'tfunds' - self.ports = [8443] + self.ports = { + 'sso' => { + 'port' => 8443 + } + } enable_ajp('8009') enable_sso('8443') disable_http_lb_hack diff --git a/spec/logstash_indexer_spec.rb b/spec/logstash_indexer_spec.rb index 59095888..567c252a 100644 --- a/spec/logstash_indexer_spec.rb +++ b/spec/logstash_indexer_spec.rb @@ -7,7 +7,11 @@ stack 'elastic_mq' do rabbitmq_cluster 'elasticmq' do # FIXME: - this should be default in rabbitmq_cluster - self.ports = [5672] + self.ports = { + 'rabbitmq' => { + 'port' => 5672 + } + } storage = { '/var/lib/rabbitmq' => { :type => 'data', :size => '100G' } diff --git a/spec/logstash_receiver_spec.rb b/spec/logstash_receiver_spec.rb index 34a52858..65d3ea1b 100644 --- a/spec/logstash_receiver_spec.rb +++ b/spec/logstash_receiver_spec.rb @@ -6,9 +6,6 @@ given do stack 'elastic_mq' do rabbitmq_cluster 'elasticmq' do - # FIXME: - this should be default in rabbitmq_cluster - self.ports = [5672] - storage = { '/var/lib/rabbitmq' => { :type => 'data', :size => '100G' } } diff --git a/spec/rabbitmq_spec.rb b/spec/rabbitmq_spec.rb index f3c097ab..f945aa88 100644 --- a/spec/rabbitmq_spec.rb +++ b/spec/rabbitmq_spec.rb @@ -232,3 +232,27 @@ eql('e2-rabbitmq-001.space.net.local,e2-rabbitmq-002.space.net.local') end end + +describe_stack 'produces the correct loadbalancer config' do + given do + stack "lb" do + loadbalancer_service + end + + stack 'rabbit' do + rabbitmq_cluster 'rabbitmq' + end + + env 'e1', :primary_site => 'space' do + instantiate_stack 'lb' + instantiate_stack 'rabbit' + end + end + + host('e1-lb-001.mgmt.space.net.local') do |host| + enc = host.to_enc['role::loadbalancer']['virtual_servers']['e1-rabbitmq-vip.space.net.local'] + expect(enc['type']).to eql('rabbitmq') + expect(enc['ports']).to eql([5672]) + expect(enc['realservers']).to eql("blue" => ["e1-rabbitmq-001", "e1-rabbitmq-002"]) + end +end diff --git a/spec/sftp_server_spec.rb b/spec/sftp_server_spec.rb index 9362853b..615d9890 100644 --- a/spec/sftp_server_spec.rb +++ b/spec/sftp_server_spec.rb @@ -9,7 +9,7 @@ stack "secureftp" do sftp_service 'sftp' do - self.ports = ['2222'] + self.ports = { 'proftpd-ssh' => { 'port' => 2222 } } end end @@ -48,7 +48,7 @@ lb_enc = load_balancer.to_enc expect(lb_enc['role::loadbalancer']['virtual_servers']['mirror-sftp-vip.oy.net.local']['persistent_ports']). to eql([]) - expect(lb_enc['role::loadbalancer']['virtual_servers']['mirror-sftp-vip.oy.net.local']['ports']).to eql(['2222']) + expect(lb_enc['role::loadbalancer']['virtual_servers']['mirror-sftp-vip.oy.net.local']['ports']).to eql([2222]) expect(lb_enc['role::loadbalancer']['virtual_servers']['mirror-sftp-vip.oy.net.local']['monitor_warn']).to eql('1') end end @@ -56,7 +56,7 @@ given do stack "secureftp" do sftp_service 'sftp' do - self.ports = ['2222'] + self.ports = { 'proftpd-ssh' => { 'port' => 2222 } } end end @@ -88,7 +88,7 @@ stack "secureftp" do sftp_service 'sftp' do - self.ports = ['2222'] + self.ports = { 'proftpd-ssh' => { 'port' => 2222 } } self.vip_warning_members = 0 end end diff --git a/spec/stacks/nat_server_spec.rb b/spec/stacks/nat_server_spec.rb index 4ca3338b..90334450 100644 --- a/spec/stacks/nat_server_spec.rb +++ b/spec/stacks/nat_server_spec.rb @@ -148,7 +148,11 @@ app_service 'blahnat' do nat_config.dnat_enabled = true depend_on 'nat', environment.name, :nat_to_vip - self.ports = [8008] + self.ports = { + 'app' => { + 'port' => '8008' + } + } end end @@ -255,7 +259,11 @@ app_service 'blahnat' do nat_config.snat_enabled = true depend_on 'nat', 'sub', :nat_to_vip - self.ports = [8008] + self.ports = { + 'app' => { + 'port' => '8008' + } + } end end @@ -333,7 +341,11 @@ standard_service 'standardwith-dnat' do extend(Stacks::Services::CanBeNatted) self.instances = 2 - self.ports = [22] + self.ports = { + 'ssh' => { + 'port' => 22 + } + } configure_dnat(:front, :mgmt, true, false) depend_on 'nat', environment.name, :nat_to_host @@ -341,7 +353,11 @@ app_service 'appwith-dnat' do self.instances = 2 - self.ports = [8000] + self.ports = { + 'app' => { + 'port' => 8000 + } + } configure_dnat(:front, :prod, true, true) depend_on 'nat', environment.name, :nat_to_vip @@ -350,7 +366,11 @@ standard_service 'standardwith-snat' do extend(Stacks::Services::CanBeNatted) self.instances = 2 - self.ports = [22] + self.ports = { + 'ssh' => { + 'port' => 22 + } + } configure_snat(:front, :mgmt, true, false) depend_on 'nat', environment.name, :nat_to_host @@ -358,7 +378,11 @@ app_service 'appwith-snat' do self.instances = 2 - self.ports = [8000] + self.ports = { + 'app' => { + 'port' => 8000 + } + } configure_snat(:front, :prod, true, false) depend_on 'nat', environment.name, :nat_to_vip @@ -366,7 +390,11 @@ app_service 'othersitewith-dnat' do self.enable_secondary_site = true - self.ports = [8443] + self.ports = { + 'app' => { + 'port' => 8443 + } + } configure_dnat(:front, :prod, true, true) @@ -382,7 +410,11 @@ app_service 'othersitewith-snat' do self.enable_secondary_site = true - self.ports = [8443] + self.ports = { + 'app' => { + 'port' => 8443 + } + } configure_snat(:front, :prod, true, true)