<commit_before>import ClusterDriver from 'shared/mixins/cluster-driver';
import { equal, alias, or } from '@ember/object/computed';
import {
  get, set, computed, observer, setProperties, defineProperty
} from '@ember/object';
import { maxSatisfying } from 'shared/utils/parse-version';
import { inject as service } from '@ember/service';
import { removeEmpty, keysToCamel, validateEndpoint, keysToDecamelize } from 'shared/utils/util';
import { validateHostname } from '@rancher/ember-api-store/utils/validate';
import { validateCertWeakly } from 'shared/utils/util';
import C from 'shared/utils/constants';
import jsyaml from 'js-yaml';
import layout from './template';
import { resolve } from 'rsvp';
import { isEmpty } from '@ember/utils';
import InputTextFile from 'ui/components/input-text-file/component';
import { scheduleOnce, once, next } from '@ember/runloop';
import { azure as AzureInfo } from 'shared/components/cru-cloud-provider/cloud-provider-info';
import moment from 'moment';
import ManageLabels from 'shared/mixins/manage-labels';
import { typeOf } from '@ember/utils';
import Semver, { major, minor }  from 'semver';
import { on } from '@ember/object/evented';
import deepSet from 'ember-deep-set';
import { coerceVersion } from 'shared/utils/parse-version';

const EXCLUDED_KEYS = ['extra_args'];

function camelToUnderline(str, split = true) {
  str = (str || '');
  if ( str.indexOf('-') > -1 || str.endsWith('CloudProvider')) {
    return str;
  } else if ( split ) {
    return (str || '').dasherize().split('-').join('_');
  } else {
    return (str || '').dasherize();
  }
}

const EXCLUED_CLUSTER_OPTIONS = [
  'annotations',
  'labels'
];

const AUTHCHOICES = [
  {
    label: 'clusterNew.rke.auth.x509',
    value: 'x509'
  },
];

const INGRESSCHOICES = [
  {
    label: 'clusterNew.rke.ingress.nginx',
    value: 'nginx'
  },
  {
    label: 'clusterNew.rke.ingress.none',
    value: 'none'
  },
];

const AVAILABLE_STRATEGIES = ['local', 's3'];

const {
  CLUSTER_TEMPLATE_IGNORED_OVERRIDES,
  NETWORK_CONFIG_DEFAULTS: { DEFAULT_BACKEND_TYPE }
} = C;

export default InputTextFile.extend(ManageLabels, ClusterDriver, {
  globalStore:                  service(),
  settings:                     service(),
  growl:                        service(),
  intl:                         service(),
  clusterTemplates:             service(),
  access:                       service(),
  router:                       service(),

  layout,
  authChoices:                  AUTHCHOICES,
  ingressChoices:               INGRESSCHOICES,
  availableStrategies:          AVAILABLE_STRATEGIES,
  ingornedRkeOverrides:         CLUSTER_TEMPLATE_IGNORED_OVERRIDES,

  configField:                  'rancherKubernetesEngineConfig',
  registry:                     'default',
  accept:                       '.yml, .yaml',
  backupStrategy:               'local',
  overrideCreatLabel:           null,
  loading:                      false,
  pasteOrUpload:                false,
  model:                        null,
  initialVersion:               null,
  registryUrl:                  null,
  registryUser:                 null,
  registryPass:                 null,
  clusterOptErrors:             null,
  nodeNameErrors:               null,

  existingNodes:                null,
  initialNodeCounts:            null,
  step:                         1,
  token:                        null,
  taints:                       null,
  labels:                       null,
  etcd:                         false,
  controlplane:                 false,
  worker:                       true,
  defaultDockerRootDir:         null,
  nodePoolErrors:               null,

  windowsEnable:                false,
  isLinux:                      true,
  weaveCustomPassword:          false,
  clusterTemplateCreate:        false,
  clusterTemplateQuestions:     null,
  forceExpandOnInit:            false,
  forceExpandAll:               false,
  applyClusterTemplate:         null,
  useClusterTemplate:           false,
  clusterTemplatesEnforced:     false,
  selectedClusterTemplateId: null,
  isNew:                        equal('mode', 'new'),
  isEdit:                       equal('mode', 'edit'),
  notView:                      or('isNew', 'isEdit'),
  clusterState:                 alias('model.originalCluster.state'),

  // Custom stuff
  isCustom:                  equal('nodeWhich', 'custom'),

  init() {
    this._super(...arguments);

    this.initNodeCounts();
    if (!this.useClusterTemplate && this.model.cluster.clusterTemplateRevisionId) {
      setProperties(this, {
        useClusterTemplate:        true,
        forceExpandOnInit:         true,
        selectedClusterTemplateId: this.cluster.clusterTemplateId,
      })
    }

    if (this.applyClusterTemplate) {
      if (this.useClusterTemplate) {
        this.initTemplateCluster();
      } else {
        this.initNonTemplateCluster();
      }
    } else {
      if (this.model.cluster.clusterTemplateRevisionId && this.router.currentRouteName !== 'global-admin.cluster-templates.new') {
        this.initTemplateCluster();
      } else {
        this.initNonTemplateCluster();
      }
    }
  },


  didReceiveAttrs() {
    if ( get(this, 'isEdit') && !get(this, 'clusterTemplateCreate')) {
      this.loadToken();
    }

    if (this.applyClusterTemplate) {
      if (this.useClusterTemplate) {
        this.initTemplateCluster();
      } else {
        if (!this.clusterTemplateCreate && isEmpty(this.cluster.rancherKubernetesEngineConfig)) {
          this.initNonTemplateCluster();
        }
      }
    }

    if (this.useClusterTemplate && this.model.cluster.clusterTemplateRevisionId) {
      set(this, 'forceExpandAll', true);
    }
  },

  actions: {
    fileUploaded() {
      let { yamlValue } = this;

      next(() => {
        set(this, 'clusterOptErrors', this.checkYamlForRkeConfig(yamlValue));
      });
    },

    yamlValUpdated(yamlValue, codeMirror) {
      if (!this.codeMirror) {
        codeMirror.on('paste', this.pastedYaml.bind(this));
      }
      // this fires when we first change over so here is where you can set the paste watcher to validate
      setProperties(this, {
        yamlValue,
        codeMirror
      });
    },

    addOverride(enabled, paramsToOverride, hideQuestion = false) {
      let {
        primaryResource,
        clusterTemplateQuestions      = [],
      }                               = this;
      let { path }                    = paramsToOverride;
      let question                    = null;
      let questionsSchemas            = [];
      let { clusterTemplateRevision } = this.model;

      if (clusterTemplateRevision && ( this.clusterTemplates.questionsSchemas || []).length > 0) {
        questionsSchemas = this.clusterTemplates.questionsSchemas;
      }

      if (enabled) {
        if (!clusterTemplateQuestions.findBy('variable', path)) {
          if (path.startsWith('uiOverride')) {
            question = questionsSchemas.findBy('variable', path);

            if (!question) {
              question = this.globalStore.createRecord({
                type:      'question',
                variable:  path,
                primaryResource,
              });
            }

            hideQuestion = true;

            setProperties(question, {
              type:    'boolean',
              default: true,
              hideQuestion
            });

            clusterTemplateQuestions.pushObject(question);
          } else {
            question = questionsSchemas.findBy('variable', path);

            if (question) {
              if (question.variable === 'rancherKubernetesEngineConfig.kubernetesVersion') {
                question = this.parseKubernetesVersionSemVer(primaryResource, question);
              }

              if (question.variable.includes('azureCloudProvider')) {
                let cloudProviderMatch = AzureInfo[(question.variable.split('.') || []).lastObject];

                if (cloudProviderMatch) {
                  let {
                    required = false,
                    type = 'string'
                  } = cloudProviderMatch;

                  question = this.globalStore.createRecord({
                    type:      'question',
                    variable:  path,
                  });

                  setProperties(question, {
                    required,
                    type,
                  });

                  if (required) {
                    set(question, 'forceRequired', true);
                  }
                }
              }
            } else {
              question = this.globalStore.createRecord({
                type:      'question',
                variable:  path,
              });

              set(question, 'type', 'string');
            }

            setProperties(question, {
              primaryResource,
              isBuiltIn: true,
              hideQuestion
            });

            if (path.includes('rancherKubernetesEngineConfig.privateRegistries[0]')) {
              // need to replace the array target with built in first object so the alias works
              path = path.replace('[0]', '.firstObject');
            }

            defineProperty(question, 'default', alias(`primaryResource.${ path }`));

            clusterTemplateQuestions.pushObject(question);
          }
        }
      } else {
        if (path === 'uiOverrideBackupStrategy') {
          question = clusterTemplateQuestions.findBy('variable', 'rancherKubernetesEngineConfig.services.etcd.backupConfig.s3BackupConfig');

          clusterTemplateQuestions.removeObject(question);
        } else {
          question = clusterTemplateQuestions.findBy('variable', path);

          clusterTemplateQuestions.removeObject(question);
        }
      }

      set(this, 'clusterTemplateQuestions', clusterTemplateQuestions);
    },

    setCpFields(configName, cloudProviderConfig) {
      set(this, `config.cloudProvider.${ configName }`, cloudProviderConfig);
    },

    cancel() {
      const newOpts = this.getOptsFromYaml();
<commit_msg>wireup ovveride row value to form value when cloning rke template<commit_after>import ClusterDriver from 'shared/mixins/cluster-driver';
import { equal, alias, or } from '@ember/object/computed';
import {
  get, set, computed, observer, setProperties, defineProperty
} from '@ember/object';
import { maxSatisfying } from 'shared/utils/parse-version';
import { inject as service } from '@ember/service';
import { removeEmpty, keysToCamel, validateEndpoint, keysToDecamelize } from 'shared/utils/util';
import { validateHostname } from '@rancher/ember-api-store/utils/validate';
import { validateCertWeakly } from 'shared/utils/util';
import C from 'shared/utils/constants';
import jsyaml from 'js-yaml';
import layout from './template';
import { resolve } from 'rsvp';
import { isEmpty } from '@ember/utils';
import InputTextFile from 'ui/components/input-text-file/component';
import { scheduleOnce, once, next } from '@ember/runloop';
import { azure as AzureInfo } from 'shared/components/cru-cloud-provider/cloud-provider-info';
import moment from 'moment';
import ManageLabels from 'shared/mixins/manage-labels';
import { typeOf } from '@ember/utils';
import Semver, { major, minor }  from 'semver';
import { on } from '@ember/object/evented';
import deepSet from 'ember-deep-set';
import { coerceVersion } from 'shared/utils/parse-version';

const EXCLUDED_KEYS = ['extra_args'];

function camelToUnderline(str, split = true) {
  str = (str || '');
  if ( str.indexOf('-') > -1 || str.endsWith('CloudProvider')) {
    return str;
  } else if ( split ) {
    return (str || '').dasherize().split('-').join('_');
  } else {
    return (str || '').dasherize();
  }
}

const EXCLUED_CLUSTER_OPTIONS = [
  'annotations',
  'labels'
];

const AUTHCHOICES = [
  {
    label: 'clusterNew.rke.auth.x509',
    value: 'x509'
  },
];

const INGRESSCHOICES = [
  {
    label: 'clusterNew.rke.ingress.nginx',
    value: 'nginx'
  },
  {
    label: 'clusterNew.rke.ingress.none',
    value: 'none'
  },
];

const AVAILABLE_STRATEGIES = ['local', 's3'];

const {
  CLUSTER_TEMPLATE_IGNORED_OVERRIDES,
  NETWORK_CONFIG_DEFAULTS: { DEFAULT_BACKEND_TYPE }
} = C;

export default InputTextFile.extend(ManageLabels, ClusterDriver, {
  globalStore:                  service(),
  settings:                     service(),
  growl:                        service(),
  intl:                         service(),
  clusterTemplates:             service(),
  access:                       service(),
  router:                       service(),

  layout,
  authChoices:                  AUTHCHOICES,
  ingressChoices:               INGRESSCHOICES,
  availableStrategies:          AVAILABLE_STRATEGIES,
  ingornedRkeOverrides:         CLUSTER_TEMPLATE_IGNORED_OVERRIDES,

  configField:                  'rancherKubernetesEngineConfig',
  registry:                     'default',
  accept:                       '.yml, .yaml',
  backupStrategy:               'local',
  overrideCreatLabel:           null,
  loading:                      false,
  pasteOrUpload:                false,
  model:                        null,
  initialVersion:               null,
  registryUrl:                  null,
  registryUser:                 null,
  registryPass:                 null,
  clusterOptErrors:             null,
  nodeNameErrors:               null,

  existingNodes:                null,
  initialNodeCounts:            null,
  step:                         1,
  token:                        null,
  taints:                       null,
  labels:                       null,
  etcd:                         false,
  controlplane:                 false,
  worker:                       true,
  defaultDockerRootDir:         null,
  nodePoolErrors:               null,

  windowsEnable:                false,
  isLinux:                      true,
  weaveCustomPassword:          false,
  clusterTemplateCreate:        false,
  clusterTemplateQuestions:     null,
  forceExpandOnInit:            false,
  forceExpandAll:               false,
  applyClusterTemplate:         null,
  useClusterTemplate:           false,
  clusterTemplatesEnforced:     false,
  selectedClusterTemplateId: null,
  isNew:                        equal('mode', 'new'),
  isEdit:                       equal('mode', 'edit'),
  notView:                      or('isNew', 'isEdit'),
  clusterState:                 alias('model.originalCluster.state'),

  // Custom stuff
  isCustom:                  equal('nodeWhich', 'custom'),

  init() {
    this._super(...arguments);

    this.initNodeCounts();
    if (!this.useClusterTemplate && this.model.cluster.clusterTemplateRevisionId) {
      setProperties(this, {
        useClusterTemplate:        true,
        forceExpandOnInit:         true,
        selectedClusterTemplateId: this.cluster.clusterTemplateId,
      })
    }

    if (this.applyClusterTemplate) {
      if (this.useClusterTemplate) {
        this.initTemplateCluster();
      } else {
        this.initNonTemplateCluster();
      }
    } else {
      if (this.model.cluster.clusterTemplateRevisionId && this.router.currentRouteName !== 'global-admin.cluster-templates.new') {
        this.initTemplateCluster();
      } else {
        this.initNonTemplateCluster();

        if (this.clusterTemplateCreate && this.clusterTemplateQuestions && this.clusterTemplateQuestions.length > 0) {
          // cloned
          this.clusterTemplateQuestions.forEach((q) => {
            this.send('addOverride', true, { path: q.variable });
          })
        }
      }
    }
  },


  didReceiveAttrs() {
    if ( get(this, 'isEdit') && !get(this, 'clusterTemplateCreate')) {
      this.loadToken();
    }

    if (this.applyClusterTemplate) {
      if (this.useClusterTemplate) {
        this.initTemplateCluster();
      } else {
        if (!this.clusterTemplateCreate && isEmpty(this.cluster.rancherKubernetesEngineConfig)) {
          this.initNonTemplateCluster();
        }
      }
    }

    if (this.useClusterTemplate && this.model.cluster.clusterTemplateRevisionId) {
      set(this, 'forceExpandAll', true);
    }
  },

  actions: {
    fileUploaded() {
      let { yamlValue } = this;

      next(() => {
        set(this, 'clusterOptErrors', this.checkYamlForRkeConfig(yamlValue));
      });
    },

    yamlValUpdated(yamlValue, codeMirror) {
      if (!this.codeMirror) {
        codeMirror.on('paste', this.pastedYaml.bind(this));
      }
      // this fires when we first change over so here is where you can set the paste watcher to validate
      setProperties(this, {
        yamlValue,
        codeMirror
      });
    },

    addOverride(enabled, paramsToOverride, hideQuestion = false) {
      let {
        primaryResource,
        clusterTemplateQuestions      = [],
      }                               = this;
      let { path }                    = paramsToOverride;
      let question                    = null;
      let questionsSchemas            = [];
      let { clusterTemplateRevision } = this.model;

      if (clusterTemplateRevision && ( this.clusterTemplates.questionsSchemas || []).length > 0) {
        questionsSchemas = this.clusterTemplates.questionsSchemas;
      }

      if (enabled) {
        if (!clusterTemplateQuestions.findBy('variable', path)) {
          if (path.startsWith('uiOverride')) {
            question = questionsSchemas.findBy('variable', path);

            if (!question) {
              question = this.globalStore.createRecord({
                type:      'question',
                variable:  path,
                primaryResource,
              });
            }

            hideQuestion = true;

            setProperties(question, {
              type:    'boolean',
              default: true,
              hideQuestion
            });

            clusterTemplateQuestions.pushObject(question);
          } else {
            question = questionsSchemas.findBy('variable', path);

            if (question) {
              if (question.variable === 'rancherKubernetesEngineConfig.kubernetesVersion') {
                question = this.parseKubernetesVersionSemVer(primaryResource, question);
              }

              if (question.variable.includes('azureCloudProvider')) {
                let cloudProviderMatch = AzureInfo[(question.variable.split('.') || []).lastObject];

                if (cloudProviderMatch) {
                  let {
                    required = false,
                    type = 'string'
                  } = cloudProviderMatch;

                  question = this.globalStore.createRecord({
                    type:      'question',
                    variable:  path,
                  });

                  setProperties(question, {
                    required,
                    type,
                  });

                  if (required) {
                    set(question, 'forceRequired', true);
                  }
                }
              }
            } else {
              question = this.globalStore.createRecord({
                type:      'question',
                variable:  path,
              });

              set(question, 'type', 'string');
            }

            setProperties(question, {
              primaryResource,
              isBuiltIn: true,
              hideQuestion
            });

            if (path.includes('rancherKubernetesEngineConfig.privateRegistries[0]')) {
              // need to replace the array target with built in first object so the alias works
              path = path.replace('[0]', '.firstObject');
            }

            defineProperty(question, 'default', alias(`primaryResource.${ path }`));

            clusterTemplateQuestions.pushObject(question);
          }
        } else {
          // we've found the template override this wires up the value displayed in overrides section to the form value
          question = clusterTemplateQuestions.findBy('variable', path);

          setProperties(question, {
            primaryResource,
            isBuiltIn: true,
            hideQuestion
          });

          defineProperty(question, 'default', alias(`primaryResource.${ path }`));
        }
      } else {
        if (path === 'uiOverrideBackupStrategy') {
          question = clusterTemplateQuestions.findBy('variable', 'rancherKubernetesEngineConfig.services.etcd.backupConfig.s3BackupConfig');

          clusterTemplateQuestions.removeObject(question);
        } else {
          question = clusterTemplateQuestions.findBy('variable', path);

          clusterTemplateQuestions.removeObject(question);
        }
      }

      set(this, 'clusterTemplateQuestions', clusterTemplateQuestions);
    },

    setCpFields(configName, cloudProviderConfig) {
      set(this, `config.cloudProvider.${ configName }`, cloudProviderConfig);
    },

    cancel() {
      const newOpts = this.getOptsFromYaml();

{'fraction_non_alphanumeric': 0.10899728221999713, 'fraction_numerical': 0.0012873694750393362, 'mean_word_length': 1.8905733186328555, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4377725', 'n_tokens_mistral': 5677, 'n_tokens_neox': 5396, 'n_words': 1108}