aboutsummaryrefslogtreecommitdiffstats
path: root/ui/imports/api/environments/environments.js
blob: 5e3b4b2c80cd1f98decf0b2db51069f38e8c38a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
/////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2017 Koren Lev (Cisco Systems), Yaron Yogev (Cisco Systems) and others /
//                                                                                      /
// All rights reserved. This program and the accompanying materials                     /
// are made available under the terms of the Apache License, Version 2.0                /
// which accompanies this distribution, and is available at                             /
// http://www.apache.org/licenses/LICENSE-2.0                                           /
/////////////////////////////////////////////////////////////////////////////////////////
import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import * as R from 'ramda';
import { Constants } from '/imports/api/constants/constants';
import { MysqlSchema } from './configuration-groups/mysql-configuration';
import { OpenStackSchema } from './configuration-groups/open-stack-configuration';
import { MonitoringSchema } from './configuration-groups/monitoring-configuration';
import { CLISchema } from './configuration-groups/cli-configuration';
import { AMQPSchema } from './configuration-groups/amqp-configuration';
//import { NfvProviderSchema } from './configuration-groups/nfv-provider-configuration';
import { AciSchema } from './configuration-groups/aci-configuration';
import {
  isMonitoringSupported,
  isListeningSupported,
} from '/imports/api/supported_environments/supported_environments';

export const Environments = new Mongo.Collection(
  'environments_config', { idGeneration: 'MONGO' });

export const requiredConfGroups = [
  'mysql',
  'OpenStack',
  'CLI',
];

export const optionalConfGroups = [
 // 'NFV_provider',
  'AMQP',
  'Monitoring',
  'ACI',
];

let simpleSchema = new SimpleSchema({
  _id: { type: { _str: { type: String, regEx: SimpleSchema.RegEx.Id } } },
  auth: {
    type: Object,
    blackbox: true,
    defaultValue: {
      'view-env': [
      ],
      'edit-env': [
      ]
    }
  },
  configuration: {
    type: [Object],
    blackbox: true,
    autoValue: function () {
      console.log('start - autovalue - environment - configuration');
      //console.log(this);
      let that = this;

      if (that.isSet) {
        let confGroups = that.value;

        let { 
          isMonitoringSupportedRes, 
          isListeningSupportedRes,
          enable_monitoring, 
          listen 
        } = extractCalcEnvSupportedRelatedValues(that);
        let dbNode = getDbNode(that);
        let aci_enabled = extractValue('aci_enabled', that, dbNode);

        if (enable_monitoring && isMonitoringSupportedRes) {
          if (! R.find(R.propEq('name', 'Monitoring'), confGroups)) {
            confGroups = R.append(createNewConfGroup('Monitoring'), confGroups);
          }
        } else {
          console.log('env - configurations - autovalue - monitoring not supported');
          confGroups = R.reject(R.propEq('name', 'Monitoring'), confGroups);
        }

        if (listen && isListeningSupportedRes) {
          if (! R.find(R.propEq('name', 'AMQP'), confGroups)) {
            confGroups = R.append(createNewConfGroup('AMQP'), confGroups);
          }
        } else {
          console.log('env - configurations - autovalue - listening not supported');
          confGroups = R.reject(R.propEq('name', 'AMQP'), confGroups);
        }

        if (aci_enabled) {
          if (! R.find(R.propEq('name', 'ACI'), confGroups)) {
            confGroups = R.append(createNewConfGroup('ACI'), confGroups);
          }
        } else {
          console.log('env - configurations - autovalue - aci not requested');
          confGroups = R.reject(R.propEq('name', 'ACI'), confGroups);
        }

        confGroups = cleanOptionalGroups(confGroups, optionalConfGroups);
        console.log('env - configurations - autovalue - after clean optional groups');

        let newValue = R.map(function(confGroup) {
          let schema = getSchemaForGroupName(confGroup.name);
          return schema.clean(confGroup);
        }, confGroups);

        console.log('end - autovalue - environment - configurations');
        console.log(newValue);
        return newValue;

      } else {
        console.log('env - configurations - autovalue - is not set');
        let newValue = R.map((confName) => {
          let schema = getSchemaForGroupName(confName);
          return schema.clean({});
        }, requiredConfGroups);
        console.log('end - autovalue - environment - configurations');
        console.log(newValue);
        return newValue;
      }
    },
    custom: function () {
      console.log('start - custom - environment - configurations');
      //console.log(this);
      let that = this;
      let configurationGroups = that.value;

      let subErrors = [];

      let { 
        isMonitoringSupportedRes, 
        isListeningSupportedRes,
        enable_monitoring, 
        listen 
      } = extractCalcEnvSupportedRelatedValues(that);

      let requiredConfGroupsTemp = R.clone(requiredConfGroups);
      if (enable_monitoring && isMonitoringSupportedRes) {
        requiredConfGroupsTemp = R.append('Monitoring', requiredConfGroupsTemp);
      }
      if (listen && isListeningSupportedRes) {
        requiredConfGroupsTemp = R.append('AMQP', requiredConfGroupsTemp);
      }

      console.log('env - configurations - custom - after mon & listen check');

      let invalidResult = R.find(function(groupName) {
        subErrors = checkGroup(groupName, configurationGroups, true);
        if (subErrors.length > 0) { return true; }
        return false;
      }, requiredConfGroupsTemp);

      console.log(`env - configurations - custom - after require groups check`);

      if (R.isNil(invalidResult)) {
        invalidResult = R.find(function(groupName) {
          subErrors = checkGroup(groupName, configurationGroups, false);
          if (subErrors.length > 0) { return true; }
          return false;
        }, optionalConfGroups);
      }

      console.log(`env - configurations - custom - after optional groups check`);

      if (! R.isNil(invalidResult)) {
        console.log(`env - configrations - custom - invalid result end: ${R.toString(subErrors)}`);
        throw {
          isError: true,
          type: 'subGroupError',
          data: subErrors,
          message: constructSubGroupErrorMessage(subErrors)
        };
      }
    },

  },
  user: {
    type: String,
  },
  distribution: {
    type: String,
    defaultValue: 'Mirantis-8.0',
    custom: function () {
      let that = this;
      let constsDist = Constants.findOne({ name: 'distributions' });

      if (R.isNil(constsDist.data)) { return 'notAllowed'; }
      let distributions = constsDist.data;

      if (R.isNil(R.find(R.propEq('value', that.value), distributions))) {
        return 'notAllowed';
      }
    },
  },
  last_scanned: {
    type: String, defaultValue: ''
  },
  name: {
    type: String,
    defaultValue: 'MyEnvironmentName',
    min: 6,
  },
  type_drivers: {
    type: String,
    defaultValue: 'gre',
    custom: function () {
      let that = this;
      let TypeDriversRec = Constants.findOne({ name: 'type_drivers' });

      if (R.isNil(TypeDriversRec.data)) { return 'notAllowed'; }
      let TypeDrivers = TypeDriversRec.data;

      if (R.isNil(R.find(R.propEq('value', that.value), TypeDrivers))) {
        return 'notAllowed';
      }
    },
  },

  mechanism_drivers: {
    type: [String],
    defaultValue: ['ovs'],
    minCount: 1,
    custom: function () {
      let that = this;
      let consts = Constants.findOne({ name: 'mechanism_drivers' });

      if (R.isNil(consts.data)) { return 'notAllowed'; }
      let mechanismDrivers = consts.data;

      let result = R.find((driver) => {
        if (R.find(R.propEq('value', driver), mechanismDrivers)) {
          return false;
        }
        return true;
      }, that.value);

      if (result) { return 'notAllowed'; }

    },
  },

  operational: {
    type: String,
    allowedValues: ['stopped', 'running', 'error'],
    defaultValue: 'stopped'
  },

  scanned: { type: Boolean, defaultValue: false },

  type: {
    type: String,
    autoValue: function () {
      return 'environment';
    },
  },

  app_path: {
    type: String,
    autoValue: function () {
      return '/home/scan/calipso_prod/app';
    }
  },

  listen: {
    type: Boolean,
    autoValue: function () {
      console.log('env - listen - autoValue - start');
      let that = this;
      let newValue = that.value;
      console.log(`- current value: ${R.toString(newValue)}`);

      let { isListeningSupportedRes } = extractCalcEnvSupportedRelatedValues(that);

      if (!isListeningSupportedRes) {
        console.log('* listening not supported');
        console.log(`* ${R.toString(isListeningSupportedRes)}`);
        newValue = false;
      }

      return newValue;
    },
  },

  enable_monitoring: {
    type: Boolean,
    autoValue: function () {
      console.log('env - enable_monitoring - autoValue - start');
      let that = this;
      let newValue = that.value;
      console.log(`- current value: ${R.toString(newValue)}`);

      let { isMonitoringSupportedRes } = extractCalcEnvSupportedRelatedValues(that);

      if (!isMonitoringSupportedRes) {
        console.log('* monitoring not supported');
        console.log(`* ${R.toString(isMonitoringSupportedRes)}`);
        newValue = false;
      }

      return newValue;
    },
  },
  aci_enabled: {
    type: Boolean,
    defaultValue: false,
  },
});

/*
simpleSchema.addValidator(function () {
  //let that = this;
});
*/

// Bug in simple schema. cant add custom message to instance specific
// schema.
// https://github.com/aldeed/meteor-simple-schema/issues/559
// Version 2 fixes it but it is rc.
//Environments.schema.messages({
SimpleSchema.messages({
  confGroupInvalid: 'Configuration group is invalid.'
});

Environments.schema = simpleSchema;
Environments.attachSchema(Environments.schema);

function getSchemaForGroupName(groupName) {
  switch (groupName) {
  case 'mysql':
    return MysqlSchema;
  case 'OpenStack':
    return OpenStackSchema;
  case 'CLI':
    return CLISchema;
  case 'AMQP':
    return AMQPSchema;
//  case 'NFV_provider':
//    return NfvProviderSchema;
  case 'ACI':
    return AciSchema;
  case 'Monitoring':
    return MonitoringSchema;
  default:
    throw 'group name is not recognized. group: ' + groupName;
  }
}

function constructSubGroupErrorMessage(errors) {
  let message = 'Validation errors on sub groups:';
  message = message + R.reduce((acc, item) => {
    return acc + '\n- ' + item.group + ': ' + item.message;
  }, '', errors);

  return message;
}

function checkGroup(groupName, configurationGroups, groupRequired) {
  let subErrors = [];
  let confGroup = R.find(R.propEq('name', groupName), configurationGroups);

  if (R.isNil(confGroup)) {
    if (groupRequired) {
      subErrors = R.append({
        field: 'configuration',
        group: groupName,
        message: 'group ' + groupName + ' is required'
      }, subErrors);
    }
    return subErrors;
  }

  let validationContext = getSchemaForGroupName(groupName).newContext();

  if (! validationContext.validate(confGroup)) {
    subErrors = R.reduce(function (acc, invalidField) {
      return R.append({
        field: invalidField,
        group: groupName,
        message: validationContext.keyErrorMessage(invalidField.name),
      }, acc);
    }, [], validationContext.invalidKeys());

    return subErrors;
  }

  return subErrors;
}

export function createNewConfGroup(groupName) {
  let schema = getSchemaForGroupName(groupName);
  return schema.clean({});
}

function cleanOptionalGroups(confGroups, optionalConfGroups) {
  return R.filter((conf) => {
    if (R.contains(conf.name, optionalConfGroups)) {
      return !isConfEmpty(conf);
    }

    return true;
  }, confGroups);
}

function isConfEmpty(conf) {
  return ! R.any((key) => {
    if (key === 'name') { return false; } // We ignore the key 'name'. It is a 'type' key.
    let val = conf[key];
    return ! ( R.isNil(val) || R.isEmpty(val));
  })(R.keys(conf));
}

function extractValue(name, schemaValidator, dbNode) {
  console.log('env - extract value');
  console.log(`-name: ${R.toString(name)}`);
  //console.log(`-schemaValidator: ${R.toString(schemaValidator)}`);
  console.log(`-dbNode: ${R.toString(dbNode)}`);

  let field = schemaValidator.field(name);
  let value = field.value;

  console.log(`extract value - schema value: ${R.toString(value)}`);

  if (R.isNil(field.value) && !field.isSet && dbNode) {
    console.log(`extract value - db value: ${R.toString(dbNode[name])}`);
    value = dbNode[name];
  }

  console.log(`extract value - result: ${R.toString(value)}`);
  return value;
}

function getDbNode(schemaHelper) {
  let _id = R.defaultTo(schemaHelper.docId, R.path(['value'], schemaHelper.field('_id')));
  let dbNode = R.defaultTo(null, Environments.findOne({ _id: _id }));
  return dbNode;
}

function extractCalcEnvSupportedRelatedValues(schemaHelper) {
  let dbNode = getDbNode(schemaHelper);

  let dist = extractValue('distribution', schemaHelper, dbNode);
  let typeDrivers = extractValue('type_drivers', schemaHelper, dbNode);
  let mechDrivers = extractValue('mechanism_drivers', schemaHelper, dbNode);
  let enable_monitoring = extractValue('enable_monitoring', schemaHelper, dbNode);
  let listen = extractValue('listen', schemaHelper, dbNode);

  let isMonitoringSupportedRes = isMonitoringSupported(dist, typeDrivers, mechDrivers);
  let isListeningSupportedRes = isListeningSupported(dist, typeDrivers, mechDrivers);

  return {
    enable_monitoring,
    listen,
    isMonitoringSupportedRes,
    isListeningSupportedRes,
  };
}