forked from ssrini/scalr
/
Farms.php
1512 lines (1291 loc) · 65 KB
/
Farms.php
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
use Scalr\Acl\Acl;
use Scalr\Farm\FarmLease;
use Scalr\Stats\CostAnalytics\Entity\CostCentreEntity;
use Scalr\Stats\CostAnalytics\Entity\CostCentrePropertyEntity;
use Scalr\Stats\CostAnalytics\Iterator\SharedProjectsFilterIterator;
use Scalr\Stats\CostAnalytics\Entity\QuarterlyBudgetEntity;
use Scalr\Stats\CostAnalytics\Quarters;
use Scalr\Stats\CostAnalytics\Entity\SettingEntity;
use Scalr\Stats\CostAnalytics\Entity\ProjectEntity;
use Scalr\Stats\CostAnalytics\Entity\AccountCostCenterEntity;
use Scalr\Model\Entity;
use Scalr\DataType\ScopeInterface;
class Scalr_UI_Controller_Farms extends Scalr_UI_Controller
{
const CALL_PARAM_NAME = 'farmId';
public function defaultAction()
{
$this->viewAction();
}
public function extendedInfoAction()
{
if (!$this->getParam('farmId'))
throw new Exception(_('Server not found'));
$dbFarm = DBFarm::LoadByID($this->getParam('farmId'));
$this->user->getPermissions()->validate($dbFarm);
$tz = $dbFarm->GetSetting(Entity\FarmSetting::TIMEZONE);
$form = array(
array(
'xtype' => 'container',
'layout' => array(
'type' => 'hbox',
'align' => 'stretch'
),
'cls' => 'x-fieldset-separator-bottom',
'items' => array(
array(
'xtype' => 'fieldset',
'title' => 'General',
'flex' => 1,
'cls' => 'x-fieldset-separator-none',
'defaults' => array(
'labelWidth' => 130
),
'items' => array(
array(
'xtype' => 'displayfield',
'fieldLabel' => 'ID',
'value' => $dbFarm->ID
),
array(
'xtype' => 'displayfield',
'fieldLabel' => 'Name',
'value' => $dbFarm->Name
),
array(
'xtype' => 'displayfield',
'fieldLabel' => 'Hash',
'value' => $dbFarm->Hash
),
array(
'xtype' => 'displayfield',
'fieldLabel' => 'Timezone',
'value' => ($tz) ? $tz : date_default_timezone_get()
)
)
)
)
)
);
///Update settings
//$scalarizrRepos = array_keys(Scalr::config('scalr.scalarizr_update.repos')); // never used in code
$repo = $dbFarm->GetSetting(Entity\FarmSetting::SZR_UPD_REPOSITORY);
if (!$repo)
$repo = Scalr::config('scalr.scalarizr_update.default_repo');
$schedule = $dbFarm->GetSetting(Entity\FarmSetting::SZR_UPD_SCHEDULE);
if (!$schedule)
$schedule = "* * *";
$sChunks = explode(" ", $schedule);
$itm = array(
'xtype' => 'fieldset',
'title' => 'Scalr agent update settings',
'flex' => 1,
'cls' => 'x-fieldset-separator-left',
'defaults' => array(
'labelWidth' => 150
),
'items' => array(
array(
'xtype' => 'displayfield',
'fieldLabel' => 'Repository',
'value' => $repo
),
array(
'xtype' => 'fieldcontainer',
'fieldLabel' => 'Schedule (UTC time)',
'layout' => 'hbox',
'defaults' => array(
'margin' => '0 6 0 0'
),
'items' => array(
array(
'xtype' => 'textfield',
'hideLabel' => true,
'readOnly' => true,
'width' => 50,
'value' => $sChunks[0],
'name' => 'hh'
), array(
'xtype' => 'textfield',
'hideLabel' => true,
'readOnly' => true,
'value' => $sChunks[1],
'width' => 50,
'name' => 'dd'
), array(
'xtype' => 'textfield',
'hideLabel' => true,
'readOnly' => true,
'width' => 50,
'value' => $sChunks[2],
'name' => 'dw',
), array(
'xtype' => 'displayinfofield',
'info' => '
* * *<br>
─ ─ ─<br>
│ │ │<br>
│ │ │<br>
│ │ └───── day of week (0 - 6) (0 is Sunday)<br>
│ └─────── day of month (1 - 31)<br>
└───────── hour (0 - 23)<br>'
)
)
)
)
);
$form[0]['items'][] = $itm;
$b = $this->db->GetAll("SELECT DISTINCT(behavior) FROM farm_roles
INNER JOIN role_behaviors ON role_behaviors.role_id = farm_roles.role_id WHERE farmid=?", array(
$this->getParam('farmId')
));
$behaviors = array();
foreach ($b as $behavior)
$behaviors[] = $behavior['behavior'];
//TODO get rid of code duplication here
$haveMysqlRole = in_array(ROLE_BEHAVIORS::MYSQL, $behaviors);
if (!$haveMysqlRole)
$haveMysql2Role = in_array(ROLE_BEHAVIORS::MYSQL2, $behaviors);
if (!$haveMysql2Role && !$haveMysqlRole)
$havePerconaRole = in_array(ROLE_BEHAVIORS::PERCONA, $behaviors);
$havePgRole = in_array(ROLE_BEHAVIORS::POSTGRESQL, $behaviors);
$haveRedisRole = in_array(ROLE_BEHAVIORS::REDIS, $behaviors);
$haveCFController = in_array(ROLE_BEHAVIORS::CF_CLOUD_CONTROLLER, $behaviors);
$type = array();
if ($havePgRole)
$type['postgresql'] = 'PostgreSQL';
if ($haveRedisRole)
$type['redis'] = 'Redis';
if ($haveMysqlRole)
$type['mysql'] = 'MySQL';
if ($haveMysql2Role)
$type['mysql2'] = 'MySQL 5.5';
if ($havePerconaRole)
$type['percona'] = 'Percona Server';
foreach ($type as $dbMsr => $name) {
$it = array(
array(
'xtype' => 'displayfield',
'anchor' => '100%',
'cls' => 'x-form-field-info',
'value' => 'Public - To connect to the service from the Internet<br / >Private - To connect to the service from another instance'
),
array(
'xtype' => 'displayfield',
'fieldLabel' => 'Writes endpoint (Public)',
'value' => "ext.master.{$dbMsr}.{$dbFarm->Hash}." . \Scalr::config('scalr.dns.static.domain_name')
),
array(
'xtype' => 'displayfield',
'fieldLabel' => 'Reads endpoint (Public)',
'value' => "ext.slave.{$dbMsr}.{$dbFarm->Hash}." . \Scalr::config('scalr.dns.static.domain_name')
),
array(
'xtype' => 'displayfield',
'fieldLabel' => 'Writes endpoint (Private)',
'value' => "int.master.{$dbMsr}.{$dbFarm->Hash}." . \Scalr::config('scalr.dns.static.domain_name')
),
array(
'xtype' => 'displayfield',
'fieldLabel' => 'Reads endpoint (Private)',
'value' => "int.slave.{$dbMsr}.{$dbFarm->Hash}." . \Scalr::config('scalr.dns.static.domain_name')
)
);
$form[] = array(
'xtype' => 'fieldset',
'title' => "{$name} DNS endpoints",
'defaults' => array(
'labelWidth' => 220
),
'items' => $it
);
}
if ($haveCFController) {
$it = array(
array(
'xtype' => 'displayfield',
'fieldLabel' => 'VMC target endpoint',
'value' => "api.ext.cloudfoundry.{$dbFarm->Hash}." . \Scalr::config('scalr.dns.static.domain_name')
)
);
$form[] = array(
'xtype' => 'fieldset',
'title' => "CloudFoundry connection information",
'defaults' => array(
'labelWidth' => 220
),
'items' => $it
);
}
$governance = new Scalr_Governance($this->getEnvironmentId());
if ($governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE) && $dbFarm->GetSetting(Entity\FarmSetting::LEASE_STATUS) && $dbFarm->Status == FARM_STATUS::RUNNING) {
$terminateDate = new DateTime($dbFarm->GetSetting(Entity\FarmSetting::LEASE_TERMINATE_DATE));
$localeTerminateDate = Scalr_Util_DateTime::convertDateTime($terminateDate, $tz, 'M j, Y');
$config = $governance->getValue(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE, null);
$standardExtend = $config['leaseExtension'] == 'allow' &&
($terminateDate->diff(new DateTime())->days < $config['defaultLifePeriod']) &&
($dbFarm->GetSetting(Entity\FarmSetting::LEASE_EXTEND_CNT) < $config['leaseExtensionStandardNumber']);
$standardExtendRemain = $config['leaseExtensionStandardNumber'] - $dbFarm->GetSetting(Entity\FarmSetting::LEASE_EXTEND_CNT);
if (
$config['leaseExtension'] == 'allow' &&
($terminateDate->diff(new DateTime())->days >= $config['defaultLifePeriod']) &&
($dbFarm->GetSetting(Entity\FarmSetting::LEASE_EXTEND_CNT) < $config['leaseExtensionStandardNumber'])
) {
$standardExtendNextDate = new DateTime($dbFarm->GetSetting(Entity\FarmSetting::LEASE_TERMINATE_DATE));
$standardExtendNextDate->sub(new DateInterval('P' . intval($config['defaultLifePeriod']) . 'D'));
$standardExtendRemain .= ' (Next will be available on ' . Scalr_Util_DateTime::convertDateTime($standardExtendNextDate, $tz, 'M j, Y') . ')';
}
$nonStandardExtend = $config['leaseExtension'] == 'allow' &&
((bool) $config['leaseExtensionNonStandard']);
$lease = new FarmLease($dbFarm);
$last = $lease->getLastRequest();
$extendInProgress = NULL;
$extendLastError = NULL;
if ($last) {
if ($last['status'] == FarmLease::STATUS_PENDING) {
$standardExtend = false;
$nonStandardExtend = false;
$extendInProgress = 'Last request was sent at ' . Scalr_Util_DateTime::convertDateTime($last['request_time'], $tz, 'M j, Y');
if ($last['request_user_email'])
$extendInProgress .= ' by ' . $last['request_user_email'];
} else if ($last['status'] == FarmLease::STATUS_DECLINE) {
$extendLastError = sprintf('Last request was declined by reason "%s"', $last['answer_comment']);
}
}
$form[] = array(
'xtype' => 'fieldset',
'title' => "Lease information",
'defaults' => array(
'labelWidth' => 220
),
'itemId' => 'lease',
'params' => array(
'farmLaunchPermission' => $this->request->isFarmAllowed($dbFarm, Acl::PERM_FARMS_LAUNCH_TERMINATE),
'standardExtend' => $standardExtend,
'standardLifePeriod' => $config['defaultLifePeriod'],
'standardExtendRemain' => $standardExtendRemain,
'nonStandardExtend' => $nonStandardExtend,
'nonStandardExtendInProgress' => $extendInProgress,
'nonStandardExtendLastError' => $extendLastError,
'terminateDate' => $terminateDate->format('Y-m-d'),
'localeTerminateDate' => $localeTerminateDate
)
);
}
$moduleParams = array(
'id' => $dbFarm->ID,
'name' => $dbFarm->Name,
'info' => $form
);
if ($this->getContainer()->analytics->enabled && $this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID)) {
$farmCostData = $this->getFarmCostData($dbFarm->ID);
$moduleParams['analytics'] = $farmCostData['analytics'];
$moduleParams['projectId'] = $farmCostData['projectId'];
$moduleParams['analytics']['farmCostMetering'] = $farmCostData['farmCostMetering'];
$c = self::loadController('Builder', 'Scalr_UI_Controller_Farms');
$moduleParams['roles'] = [];
foreach ($c->getFarm2($dbFarm->ID)['roles'] as $role) {
$moduleParams['roles'][] = [
'platform' => $role['platform'],
'alias' => $role['alias'],
'running_servers' => $role['running_servers'],
'suspended_servers' => $role['suspended_servers'],
'hourly_rate' => $role['hourly_rate'],
Entity\FarmRoleSetting::SCALING_ENABLED => $role['settings'][Entity\FarmRoleSetting::SCALING_ENABLED],
Entity\FarmRoleSetting::SCALING_MIN_INSTANCES => $role['settings'][Entity\FarmRoleSetting::SCALING_MIN_INSTANCES],
Entity\FarmRoleSetting::SCALING_MAX_INSTANCES => $role['settings'][Entity\FarmRoleSetting::SCALING_MAX_INSTANCES],
Scalr_Role_Behavior::ROLE_BASE_CONSIDER_SUSPENDED => $role['settings'][Scalr_Role_Behavior::ROLE_BASE_CONSIDER_SUSPENDED]
];
}
}
$this->response->page('ui/farms/extendedinfo.js', $moduleParams,
array('ui/farms/builder/costmetering.js')/*, array('ui/analytics/analytics.css')*/);
}
public function xLeaseExtendAction()
{
if (!$this->getParam('farmId'))
throw new Exception(_('Server not found'));
$dbFarm = DBFarm::LoadByID($this->getParam('farmId'));
$this->user->getPermissions()->validate($dbFarm);
$this->request->restrictFarmAccess($dbFarm, Acl::PERM_FARMS_LAUNCH_TERMINATE);
$governance = new Scalr_Governance($this->getEnvironmentId());
if (! ($governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE) && $dbFarm->GetSetting(Entity\FarmSetting::LEASE_STATUS) && $dbFarm->Status == FARM_STATUS::RUNNING))
throw new Scalr_Exception_Core('You can\'t manage lease for this farm');
$config = $governance->getValue(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE, null);
$terminateDate = new DateTime($dbFarm->GetSetting(Entity\FarmSetting::LEASE_TERMINATE_DATE));
if ($config['leaseExtension'] != 'allow')
throw new Scalr_Exception_Core('You can\'t extend lease for this farm');
if ($this->getParam('extend') == 'standard') {
$standardExtend = ($terminateDate->diff(new DateTime())->days < $config['defaultLifePeriod']) &&
($dbFarm->GetSetting(Entity\FarmSetting::LEASE_EXTEND_CNT) < $config['leaseExtensionStandardNumber']);
if ($standardExtend) {
$terminateDate->add(new DateInterval('P' . intval($config['defaultLifePeriod']) . 'D'));
$dbFarm->SetSetting(Entity\FarmSetting::LEASE_EXTEND_CNT, $dbFarm->GetSetting(Entity\FarmSetting::LEASE_EXTEND_CNT) + 1);
$dbFarm->SetSetting(Entity\FarmSetting::LEASE_TERMINATE_DATE, $terminateDate->format('Y-m-d H:i:s'));
$dbFarm->SetSetting(Entity\FarmSetting::LEASE_NOTIFICATION_SEND, null);
Entity\SettingEntity::increase(Entity\SettingEntity::LEASE_STANDARD_REQUEST);
$this->response->success('Farm expiration date was changed');
} else {
$this->response->failure('Limit of changes was reached');
}
} else if ($this->getParam('extend') == 'non-standard') {
$lease = new FarmLease($dbFarm);
$comment = $this->getParam('comment');
$last = $lease->getLastRequest();
if ($last && $last['status'] == FarmLease::STATUS_PENDING) {
$this->response->failure('You\'ve already made expiration request. Before make another one, wait for answer.');
} else {
if ($this->getParam('by') == 'days' && intval($this->getParam('byDays')) > 0) {
$lease->addRequest(intval($this->getParam('byDays')), $comment, $this->user->getId());
} else if ($this->getParam('by') == 'date' && strtotime($this->getParam('byDate'))) {
$dt = new DateTime($this->getParam('byDate'));
$lease->addRequest($terminateDate->diff($dt)->days, $comment, $this->user->getId());
} else if ($this->getParam('by') == 'forever') {
$lease->addRequest(0, $comment, $this->user->getId());
} else {
throw new Scalr_Exception_Core('Invalid period format');
}
Entity\SettingEntity::increase(Entity\SettingEntity::LEASE_NOT_STANDARD_REQUEST);
$mailer = Scalr::getContainer()->mailer;
if ($this->getContainer()->config('scalr.auth_mode') == 'ldap') {
$owner = $this->user->getAccount()->getOwner();
if ($owner->getSetting(Scalr_Account_User::SETTING_LDAP_EMAIL))
$mailer->addTo($owner->getSetting(Scalr_Account_User::SETTING_LDAP_EMAIL));
else
$mailer->addTo($owner->getEmail());
} else {
$mailer->addTo($this->user->getAccount()->getOwner()->getEmail());
}
if ($config['leaseExtensionNonStandardNotifyEmails']) {
$emails = explode(',', $config['leaseExtensionNonStandardNotifyEmails']);
foreach ($emails as $email) {
$email = trim($email);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$mailer->addTo($email);
}
}
}
$mailer->sendTemplate(
SCALR_TEMPLATES_PATH . '/emails/farm_lease_non_standard_request.eml',
array(
'{{farm_name}}' => $dbFarm->Name,
'{{user_name}}' => $this->user->getEmail(),
'{{comment}}' => $comment,
'{{envName}}' => $dbFarm->GetEnvironmentObject()->name,
'{{envId}}' => $dbFarm->GetEnvironmentObject()->id
)
);
$this->response->success('Farm expiration request was sent');
}
} else if ($this->getParam('extend') == 'cancel') {
$lease = new FarmLease($dbFarm);
if ($lease->cancelLastRequest())
$this->response->success('Non-standard extend was cancelled');
else
$this->response->failure('Last request wasn\'t found');
} else {
$this->response->failure('Invalid extend type');
}
}
public function getList(array $filterArgs = array())
{
$retval = array();
$sql = "SELECT name, id FROM farms WHERE env_id = ?";
$args = array($this->getEnvironmentId());
foreach ((array)$filterArgs as $k => $v) {
if (!empty($v) && is_array($v)) {
foreach ($v as $vv) {
array_push($args, $vv);
}
$sql .= " AND `{$k}` IN (". join(",", array_fill(0, count($v), "?")) . ")";
} else {
$sql .= " AND `{$k}`=?";
array_push($args, $v);
}
}
list($sql, $args) = $this->request->prepareFarmSqlQuery($sql, $args);
$sql .= " ORDER BY name, id";
$s = $this->db->execute($sql, $args);
while ($farm = $s->fetchRow()) {
$retval[] = $farm;
}
return $retval;
}
/**
* @param array $values (farmId, farmRoleId, serverId)
* @param array|string $options
* 'addAll' - add "On all *" option to roles and servers
* 'addAllFarms' - add "On all farms" options to farms
* 'disabledFarmRole' - remove farmRole field
* 'disabledServer' - remove server field
* 'addEmpty' - add "*empty*" option (to all lists)
* 'addEmptyFarm' - add "*empty*" options to farms list only
* 'requiredFarm', 'requiredFarmRole', 'requiredServer' - add allowBlank = false to field
* @return array
*/
// TODO: may be move to separated class
public function getFarmWidget($values = array(), $options)
{
if ($options) {
if (!is_array($options))
$options = array($options);
} else
$options = array();
if ($values['serverId']) {
try {
$dbServer = DBServer::LoadByID($values['serverId']);
$this->user->getPermissions()->validate($dbServer);
$values['farmRoleId'] = $dbServer->farmRoleId;
} catch (Exception $e) {}
}
if ($values['farmRoleId']) {
try {
$dbFarmRole = DBFarmRole::LoadByID($values['farmRoleId']);
$this->user->getPermissions()->validate($dbFarmRole);
$values['dataServers'] = $this->getFarmWidgetServers($values['farmRoleId'], $options);
$values['farmId'] = $dbFarmRole->FarmID;
if (! $values['serverId'])
$values['serverId'] = 0;
} catch (Exception $e) {}
}
if ($values['farmId']) {
$values['dataFarmRoles'] = $this->getFarmWidgetRoles($values['farmId'], $options);
}
$values['dataFarms'] = $this->getFarmWidgetFarms($options);
$values['options'] = $options;
return $values;
}
public function getFarmWidgetFarms($options)
{
$perm = in_array('permServers', $options) ? Acl::PERM_FARMS_SERVERS : null;
$sql = 'SELECT id, name FROM farms WHERE env_id = ?';
$args = [$this->getEnvironmentId()];
list($sql, $args) = $this->request->prepareFarmSqlQuery($sql, $args, '', $perm);
$sql .= ' ORDER BY name';
$farms = $this->db->GetAll($sql, $args);
if (in_array('addAllFarm', $options))
array_unshift($farms, array('id' => '0', 'name' => 'On all farms'));
if (in_array('addEmpty', $options) || in_array('addEmptyFarm', $options))
array_unshift($farms, array('id' => '', 'name' => ''));
return $farms;
}
public function getFarmWidgetRoles($farmId, $options)
{
$dbFarm = DBFarm::LoadById($farmId);
$this->user->getPermissions()->validate($dbFarm);
$dataFarmRoles = array();
$behaviors = array();
foreach($options as $key => $value) {
$matches = explode('_', $value);
if ($matches[0] == 'behavior' && $matches[1])
$behaviors[] = $matches[1];
}
foreach($this->db->GetAll("SELECT id, platform, role_id, alias AS name FROM farm_roles WHERE farmid = ?", array($dbFarm->ID)) as $farmRole) {
try {
$dbRole = DBRole::loadById($farmRole['role_id']);
if (!empty($behaviors)) {
$bFilter = false;
foreach($behaviors as $behavior) {
if ($dbRole->hasBehavior($behavior)) {
$bFilter = true;
break;
}
}
if (!$bFilter)
continue;
}
} catch (Exception $e) {
$farmRole['name'] = '*removed*';
}
array_push($dataFarmRoles, $farmRole);
}
if (count($dataFarmRoles) && in_array('addAll', $options))
array_unshift($dataFarmRoles, array('id' => '0', 'name' => 'On all roles'));
if (in_array('addEmpty', $options))
array_unshift($dataFarmRoles, array('id' => '', 'name' => ''));
if (!empty($dataFarmRoles))
return $dataFarmRoles;
else
return null;
}
//todo: restrictAccess check?
public function xGetFarmWidgetRolesAction()
{
$this->response->data(array(
'dataFarmRoles' => $this->getFarmWidgetRoles($this->getParam('farmId'), explode(',', $this->getParam('options')))
));
}
public function getFarmWidgetServers($farmRoleId, $options)
{
$servers = array();
$dbFarmRole = DBFarmRole::LoadByID($farmRoleId);
$this->user->getPermissions()->validate($dbFarmRole);
foreach ($dbFarmRole->GetServersByFilter(array('status' => SERVER_STATUS::RUNNING)) as $value) {
array_push($servers, array('id' => $value->serverId, 'name' => $value->getNameByConvention()));
}
if (count($servers) && in_array('addAll', $options)) {
array_unshift($servers, array('id' => 0, 'name' => 'All instances of this Farm Role'));
}
if (in_array('addEmpty', $options))
array_unshift($servers, array('id' => '', 'name' => ''));
if (!empty($servers))
return $servers;
else
return null;
}
//todo: restrictAccess check?
public function xGetFarmWidgetServersAction()
{
$this->response->data(array(
'dataServers' => $this->getFarmWidgetServers($this->getParam('farmRoleId'), explode(',', $this->getParam('options')))
));
}
public function viewAction()
{
$this->request->restrictFarmAccess();
$governance = new Scalr_Governance($this->getEnvironmentId());
$this->response->page('ui/farms/view.js', array('leaseEnabled' => $governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE)));
}
public function dnszonesAction()
{
$this->request->setParams(array('farmId' => $this->getParam('farmId')));
self::loadController('Dnszones')->viewAction();
}
public function vhostsAction()
{
$this->request->setParams(array('farmId' => $this->getParam('farmId')));
self::loadController('Vhosts', 'Scalr_UI_Controller_Services_Apache')->viewAction();
}
public function serversAction()
{
$this->request->setParams(array('farmId' => $this->getParam('farmId')));
self::loadController('Servers')->viewAction();
}
/**
* @param int $farmId
*/
public function xCloneAction($farmId)
{
$dbFarm = DBFarm::LoadByID($farmId);
$this->user->getPermissions()->validate($dbFarm);
$this->request->restrictFarmAccess($dbFarm, Acl::PERM_FARMS_CLONE);
$newDbFarm = $dbFarm->cloneFarm(null, $this->user, $this->getEnvironmentId());
$this->response->success("Farm successfully cloned. New farm: '{$newDbFarm->Name}'");
}
/**
* @param int $farmId
* @param string $comment
* @param string $restrict
*/
public function xLockAction($farmId, $comment, $restrict = '')
{
if (! $comment) {
$this->response->failure('Comment is required');
return;
}
if (! in_array($restrict, ['', 'team', 'owner'])) {
$this->response->failure('Restrict should be owner, team or empty string');
return;
}
$dbFarm = DBFarm::LoadByID($farmId);
$this->user->getPermissions()->validate($dbFarm);
$this->request->restrictFarmAccess($dbFarm, Acl::PERM_FARMS_MANAGE);
$dbFarm->isLocked();
$dbFarm->lock($this->user->getId(), $comment, $restrict);
$this->response->success('Farm successfully locked');
}
/**
* @param int $farmId
* @throws Exception
*/
public function xUnlockAction($farmId)
{
$dbFarm = DBFarm::LoadByID($farmId);
$this->user->getPermissions()->validate($dbFarm);
$this->request->restrictFarmAccess($dbFarm, Acl::PERM_FARMS_MANAGE);
if ($dbFarm->isLocked(false)) {
$restrict = $dbFarm->GetSetting(Entity\FarmSetting::LOCK_RESTRICT);
if ($restrict && !$this->user->isAccountOwner()) {
if ($restrict == 'owner') {
if ($dbFarm->createdByUserId != $this->user->getId()) {
throw new Exception('You can\'t unlock this Farm. Only the Farm Owner or an Account Owner may do so.');
}
}
if ($restrict == 'team') {
if (!$this->user->isInTeam($dbFarm->teamId)) {
throw new Exception('You can\'t unlock this Farm. Only the members of the Farm\'s Team or an Account Owner may do so.');
}
}
}
$dbFarm->unlock($this->user->getId());
$this->response->success('Farm successfully unlocked');
} else {
$this->response->failure('Farm isn\'t locked');
}
}
/**
* @param int $farmId
* @param string $deleteDNSZones
* @param string $deleteCloudObjects
* @param string $unTermOnFail
* @param string $forceTerminate
*/
public function xTerminateAction($farmId, $deleteDNSZones = '', $deleteCloudObjects = '', $unTermOnFail = '', $forceTerminate = '')
{
$dbFarm = DBFarm::LoadByID($farmId);
$this->user->getPermissions()->validate($dbFarm);
$this->request->restrictFarmAccess($dbFarm, Acl::PERM_FARMS_LAUNCH_TERMINATE);
$dbFarm->isLocked();
$removeZoneFromDNS = ($deleteDNSZones == 'on') ? 1 : 0;
$keepCloudObjects = ($deleteCloudObjects == 'on') ? 0 : 1;
$termOnFail = ($unTermOnFail == 'on') ? 0 : 1;
$forceTerminate = ($forceTerminate == 'on') ? 1 : 0;
Scalr::FireEvent($farmId, new FarmTerminatedEvent(
$removeZoneFromDNS,
$keepCloudObjects,
$termOnFail,
$keepCloudObjects,
$forceTerminate,
$this->user->id
));
$this->response->success('Farm successfully terminated. Instances termination can take a few minutes.');
}
/**
* @param int $farmId
*/
public function xGetTerminationDetailsAction($farmId)
{
$dbFarm = DBFarm::LoadByID($farmId);
$this->user->getPermissions()->validate($dbFarm);
$this->request->restrictFarmAccess($dbFarm, Acl::PERM_FARMS_LAUNCH_TERMINATE);
$dbFarm->isLocked();
$outdatedFarmRoles = $this->db->GetAll("SELECT id FROM farm_roles WHERE farmid=?",
array($dbFarm->ID)
);
$data = array();
$isMongoDbClusterRunning = false;
$isMysql = false;
$isRabbitMQ = false;
foreach ($outdatedFarmRoles as $farmRole) {
$dbFarmRole = DBFarmRole::LoadByID($farmRole['id']);
if (!$isMongoDbClusterRunning) {
$isMongoDbClusterRunning = $dbFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MONGODB) && ($dbFarmRole->GetSetting(Scalr_Role_Behavior_MongoDB::ROLE_CLUSTER_STATUS) != Scalr_Role_Behavior_MongoDB::STATUS_TERMINATED);
}
if (!$isMysql) {
$isMysql = $dbFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MYSQL);
}
if (!$isRabbitMQ) {
$isRabbitMQ = $dbFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::RABBITMQ);
}
$row = array(
'dtLastSync' => (strtotime($dbFarmRole->dtLastSync) ?
Scalr_Util_DateTime::getFuzzyTime(strtotime($dbFarmRole->dtLastSync), false) :
"Never"),
'name' => $dbFarmRole->GetRoleObject()->name,
'id' => $dbFarmRole->ID,
'isBundleRunning' => $this->db->GetOne("
SELECT id FROM bundle_tasks
WHERE status NOT IN ('success','failed')
AND role_id=?
AND farm_id IN (SELECT id FROM farms WHERE client_id=?)
", array(
$dbFarmRole->RoleID,
$dbFarm->ClientID
))
);
foreach ($dbFarmRole->GetServersByFilter(array('status' => SERVER_STATUS::RUNNING)) as $dbServer) {
$row['servers'][] = array(
'server_id' => $dbServer->serverId,
'remoteIp' => $dbServer->remoteIp
);
}
$data[] = $row;
}
$this->response->data(array(
'roles' => $data,
'isMongoDbClusterRunning' => $isMongoDbClusterRunning,
'isMysqlRunning' => $isMysql,
'isRabbitMQ' => $isRabbitMQ,
'farmId' => $dbFarm->ID,
'farmName' => $dbFarm->Name
));
}
/**
* @param int $farmId
*/
public function xLaunchAction($farmId)
{
$dbFarm = DBFarm::LoadByID($farmId);
$this->user->getPermissions()->validate($dbFarm);
$this->request->restrictFarmAccess($dbFarm, Acl::PERM_FARMS_LAUNCH_TERMINATE);
$dbFarm->isLocked();
Scalr::FireEvent($dbFarm->ID, new FarmLaunchedEvent(true, $this->user->id));
$this->response->success('Farm successfully launched');
}
/**
* @param int $farmId
* @throws Exception
* @throws Scalr_Exception_InsufficientPermissions
*/
public function xRemoveAction($farmId)
{
$dbFarm = DBFarm::LoadByID($farmId);
$this->user->getPermissions()->validate($dbFarm);
$this->request->restrictFarmAccess($dbFarm, Acl::PERM_FARMS_MANAGE);
$dbFarm->isLocked();
if ($dbFarm->Status != FARM_STATUS::TERMINATED)
throw new Exception(_("Cannot delete a running farm. Please terminate a farm before deleting it."));
$servers = $this->db->GetOne("SELECT COUNT(*) FROM servers WHERE farm_id=? AND status!=?", array($dbFarm->ID, SERVER_STATUS::TERMINATED));
if ($servers != 0)
throw new Exception(sprintf(_("Cannot delete a running farm. %s server%s still running on this farm."), $servers, $servers > 1 ? 's are' : ' is'));
$this->db->BeginTrans();
try
{
foreach ($this->db->GetAll("SELECT * FROM farm_roles WHERE farmid = ?", array($dbFarm->ID)) as $value) {
$this->db->Execute("DELETE FROM scheduler WHERE target_id = ? AND target_type IN(?,?)", array(
$value['id'],
Scalr_SchedulerTask::TARGET_ROLE,
Scalr_SchedulerTask::TARGET_INSTANCE
));
}
$this->db->Execute("DELETE FROM scheduler WHERE target_id = ? AND target_type = ?", array(
$dbFarm->ID,
Scalr_SchedulerTask::TARGET_FARM
));
//We should not remove farm_settings because it is used in stats!
$this->db->Execute("DELETE FROM farms WHERE id=?", array($dbFarm->ID));
$this->db->Execute("DELETE FROM farm_roles WHERE farmid=?", array($dbFarm->ID));
$this->db->Execute("DELETE FROM logentries WHERE farmid=?", array($dbFarm->ID));
$this->db->Execute("DELETE FROM elastic_ips WHERE farmid=?", array($dbFarm->ID));
$this->db->Execute("DELETE FROM events WHERE farmid=?", array($dbFarm->ID));
$this->db->Execute("DELETE FROM ec2_ebs WHERE farm_id=?", array($dbFarm->ID));
$this->db->Execute("DELETE FROM farm_role_scripts WHERE farmid=?", array($dbFarm->ID));
$this->db->Execute("DELETE FROM farm_lease_requests WHERE farm_id=?", array($dbFarm->ID));
//TODO: Remove servers
$servers = $this->db->Execute("SELECT server_id FROM servers WHERE farm_id=?", array($dbFarm->ID));
while ($server = $servers->FetchRow()) {
$dbServer = DBServer::LoadByID($server['server_id']);
$dbServer->Remove();
}
$this->db->Execute("UPDATE dns_zones SET farm_id='0', farm_roleid='0' WHERE farm_id=?", array($dbFarm->ID));
$this->db->Execute("UPDATE apache_vhosts SET farm_id='0', farm_roleid='0' WHERE farm_id=?", array($dbFarm->ID));
} catch(Exception $e) {
$this->db->RollbackTrans();
throw new Exception(_("Cannot delete farm at the moment ({$e->getMessage()}). Please try again later."));
}
$this->db->CommitTrans();
$this->db->Execute("DELETE FROM scripting_log WHERE farmid=?", array($dbFarm->ID));
$this->response->success('Farm successfully removed');
}
public function xListFarmsAction()
{
$this->request->restrictFarmAccess();
$this->request->defineParams(array(
'clientId' => array('type' => 'int'),
'farmId' => array('type' => 'int'),
'sort' => array('type' => 'json'),
'expirePeriod' => array('type' => 'int')
));
$governance = new Scalr_Governance($this->getEnvironmentId());
$leaseStatus = $governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE);
$sql = 'SELECT f.clientid, f.id, f.name, f.status, f.dtadded, f.created_by_id, f.created_by_email, ats.name AS team_name, ats.description AS team_description, ats.id as team_id FROM farms f LEFT JOIN account_teams ats ON ats.id = f.team_id WHERE env_id = ? AND :FILTER:';
$args = array($this->getEnvironmentId());
if ($leaseStatus && $this->getParam('expirePeriod')) {
$dt = new DateTime();
$dt->add(new DateInterval('P' . $this->getParam('expirePeriod') . 'D'));
$sql = str_replace('FROM farms f', 'FROM farms f LEFT JOIN farm_settings fs ON f.id = fs.farmid', $sql);
$sql = str_replace('WHERE', 'WHERE fs.name = ? AND fs.value < ? AND fs.value != "" AND f.status = ? AND', $sql);
array_unshift($args, Entity\FarmSetting::LEASE_TERMINATE_DATE, $dt->format('Y-m-d H:i:s'), FARM_STATUS::RUNNING);
}
if ($this->getParam('farmId')) {
$sql .= ' AND f.id = ?';
$args[] = $this->getParam('farmId');
}
if ($this->getParam('clientId')) {
$sql .= ' AND clientid = ?';
$args[] = $this->getParam('clientId');
}
if ($this->getParam('status') != '') {
$sql .= ' AND status = ?';
$args[] = $this->getParam('status');
}
$owner = $this->getParam('owner');
$permission = $this->getParam('manageable') ? Acl::PERM_FARMS_MANAGE : null;
$allowedResourceFarms = $this->request->isAllowed(Acl::RESOURCE_FARMS, $permission);
if (!$allowedResourceFarms || $owner) {
$q = [];
if (($this->request->isAllowed(Acl::RESOURCE_TEAM_FARMS, $permission) || $allowedResourceFarms) && ($owner == '' || $owner == 'team')) {
$t = array_map(function($t) { return $t['id']; }, $this->user->getTeams());
if (count($t))
$q[] = 'team_id IN(' . join(',', $t) . ')';
}
if (($this->request->isAllowed(Acl::RESOURCE_OWN_FARMS, $permission) || $allowedResourceFarms) && ($owner == '' || $owner == 'me')) {
$q[] = 'created_by_id = ?';
$args[] = $this->request->getUser()->getId();
}
if (count($q)) {
$sql .= ' AND (' . join(' OR ', $q) . ')';
} else {
$sql .= ' AND false'; // no permissions
}
}
if ($this->getParam('chefServerId')) {
$sql .= ' AND f.id IN (
SELECT fr.farmid
FROM farm_roles fr
INNER JOIN farm_role_settings frs1 ON fr.id = frs1.farm_roleid AND frs1.name = ? AND frs1.value = ?
INNER JOIN farm_role_settings frs2 ON fr.id = frs2.farm_roleid AND frs2.name = ? AND frs2.value = ?
)';
$args[] = \Scalr_Role_Behavior_Chef::ROLE_CHEF_SERVER_ID;