forked from apache/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathUpgrade410to420.java
More file actions
2632 lines (2496 loc) · 161 KB
/
Upgrade410to420.java
File metadata and controls
2632 lines (2496 loc) · 161 KB
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.upgrade.dao;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider;
import com.cloud.deploy.DeploymentPlanner;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.vpc.NetworkACL;
import com.cloud.utils.Pair;
import com.cloud.utils.crypt.DBEncryptionUtil;
import com.cloud.utils.exception.CloudRuntimeException;
public class Upgrade410to420 extends DbUpgradeAbstractImpl {
@Override
public String[] getUpgradableVersionRange() {
return new String[] {"4.1.0", "4.2.0"};
}
@Override
public String getUpgradedVersion() {
return "4.2.0";
}
@Override
public boolean supportsRollingUpgrade() {
return false;
}
@Override
public InputStream[] getPrepareScripts() {
final String scriptFile = "META-INF/db/schema-410to420.sql";
final InputStream script = Thread.currentThread().getContextClassLoader().getResourceAsStream(scriptFile);
if (script == null) {
throw new CloudRuntimeException("Unable to find " + scriptFile);
}
return new InputStream[] {script};
}
@Override
public void performDataMigration(Connection conn) {
movePrivateZoneToDedicatedResource(conn);
upgradeVmwareLabels(conn);
persistLegacyZones(conn);
persistVswitchConfiguration(conn);
createPlaceHolderNics(conn);
updateRemoteAccessVpn(conn);
updateOverCommitRatioClusterDetails(conn);
updatePrimaryStore(conn);
addEgressFwRulesForSRXGuestNw(conn);
upgradeEIPNetworkOfferings(conn);
updateGlobalDeploymentPlanner(conn);
upgradeDefaultVpcOffering(conn);
upgradePhysicalNtwksWithInternalLbProvider(conn);
updateNetworkACLs(conn);
addHostDetailsIndex(conn);
updateNetworksForPrivateGateways(conn);
correctExternalNetworkDevicesSetup(conn);
removeFirewallServiceFromSharedNetworkOfferingWithSGService(conn);
fix22xKVMSnapshots(conn);
setKVMSnapshotFlag(conn);
addIndexForAlert(conn);
fixBaremetalForeignKeys(conn);
// storage refactor related migration
// TODO: add clean-up scripts to delete the deprecated table.
migrateSecondaryStorageToImageStore(conn);
migrateVolumeHostRef(conn);
migrateTemplateHostRef(conn);
migrateSnapshotStoreRef(conn);
migrateS3ToImageStore(conn);
migrateSwiftToImageStore(conn);
fixNiciraKeys(conn);
fixRouterKeys(conn);
encryptSite2SitePSK(conn);
migrateDatafromIsoIdInVolumesTable(conn);
setRAWformatForRBDVolumes(conn);
migrateVolumeOnSecondaryStorage(conn);
createFullCloneFlag(conn);
upgradeVpcServiceMap(conn);
upgradeResourceCount(conn);
}
private void createFullCloneFlag(Connection conn) {
String update_sql;
int numRows = 0;
try (PreparedStatement delete = conn.prepareStatement("delete from `cloud`.`configuration` where name='vmware.create.full.clone';");)
{
delete.executeUpdate();
try(PreparedStatement query = conn.prepareStatement("select count(*) from `cloud`.`data_center`");)
{
try(ResultSet rs = query.executeQuery();) {
if (rs.next()) {
numRows = rs.getInt(1);
}
if (numRows > 0) {
update_sql = "insert into `cloud`.`configuration` (`category`, `instance`, `component`, `name`, `value`, `description`) VALUES ('Advanced', 'DEFAULT', 'UserVmManager', 'vmware.create.full.clone' , 'false', 'If set to true, creates VMs as full clones on ESX hypervisor');";
} else {
update_sql = "insert into `cloud`.`configuration` (`category`, `instance`, `component`, `name`, `value`, `description`) VALUES ('Advanced', 'DEFAULT', 'UserVmManager', 'vmware.create.full.clone' , 'true', 'If set to true, creates VMs as full clones on ESX hypervisor');";
}
try(PreparedStatement update_pstmt = conn.prepareStatement(update_sql);) {
update_pstmt.executeUpdate();
}catch (SQLException e) {
throw new CloudRuntimeException("Failed to set global flag vmware.create.full.clone: ", e);
}
}catch (SQLException e) {
throw new CloudRuntimeException("Failed to set global flag vmware.create.full.clone: ", e);
}
}catch (SQLException e) {
throw new CloudRuntimeException("Failed to set global flag vmware.create.full.clone: ", e);
}
} catch (SQLException e) {
throw new CloudRuntimeException("Failed to set global flag vmware.create.full.clone: ", e);
}
}
private void migrateVolumeOnSecondaryStorage(Connection conn) {
try (PreparedStatement sql = conn.prepareStatement("update `cloud`.`volumes` set state='Uploaded' where state='UploadOp'");){
sql.executeUpdate();
} catch (SQLException e) {
throw new CloudRuntimeException("Failed to upgrade volume state: ", e);
}
}
private void persistVswitchConfiguration(Connection conn) {
Long clusterId;
String clusterHypervisorType;
final String NEXUS_GLOBAL_CONFIG_PARAM_NAME = "vmware.use.nexus.vswitch";
final String DVS_GLOBAL_CONFIG_PARAM_NAME = "vmware.use.dvswitch";
final String VSWITCH_GLOBAL_CONFIG_PARAM_CATEGORY = "Network";
final String VMWARE_STANDARD_VSWITCH = "vmwaresvs";
final String NEXUS_1000V_DVSWITCH = "nexusdvs";
String paramValStr;
boolean readGlobalConfigParam = false;
boolean nexusEnabled = false;
String publicVswitchType = VMWARE_STANDARD_VSWITCH;
String guestVswitchType = VMWARE_STANDARD_VSWITCH;
Map<Long, List<Pair<String, String>>> detailsMap = new HashMap<Long, List<Pair<String, String>>>();
List<Pair<String, String>> detailsList;
try (PreparedStatement clustersQuery = conn.prepareStatement("select id, hypervisor_type from `cloud`.`cluster` where removed is NULL");){
try(ResultSet clusters = clustersQuery.executeQuery();) {
while (clusters.next()) {
clusterHypervisorType = clusters.getString("hypervisor_type");
clusterId = clusters.getLong("id");
if (clusterHypervisorType.equalsIgnoreCase("VMware")) {
if (!readGlobalConfigParam) {
paramValStr = getConfigurationParameter(conn, VSWITCH_GLOBAL_CONFIG_PARAM_CATEGORY, NEXUS_GLOBAL_CONFIG_PARAM_NAME);
if (paramValStr.equalsIgnoreCase("true")) {
nexusEnabled = true;
}
}
if (nexusEnabled) {
publicVswitchType = NEXUS_1000V_DVSWITCH;
guestVswitchType = NEXUS_1000V_DVSWITCH;
}
detailsList = new ArrayList<Pair<String, String>>();
detailsList.add(new Pair<String, String>(ApiConstants.VSWITCH_TYPE_GUEST_TRAFFIC, guestVswitchType));
detailsList.add(new Pair<String, String>(ApiConstants.VSWITCH_TYPE_PUBLIC_TRAFFIC, publicVswitchType));
detailsMap.put(clusterId, detailsList);
updateClusterDetails(conn, detailsMap);
logger.debug("Persist vSwitch Configuration: Successfully persisted vswitch configuration for cluster " + clusterId);
} else {
logger.debug("Persist vSwitch Configuration: Ignoring cluster " + clusterId + " with hypervisor type " + clusterHypervisorType);
continue;
}
} // End cluster iteration
}catch (SQLException e) {
String msg = "Unable to persist vswitch configuration of VMware clusters." + e.getMessage();
logger.error(msg);
throw new CloudRuntimeException(msg, e);
}
if (nexusEnabled) {
// If Nexus global parameter is true, then set DVS configuration parameter to true. TODOS: Document that this mandates that MS need to be restarted.
setConfigurationParameter(conn, VSWITCH_GLOBAL_CONFIG_PARAM_CATEGORY, DVS_GLOBAL_CONFIG_PARAM_NAME, "true");
}
} catch (SQLException e) {
String msg = "Unable to persist vswitch configuration of VMware clusters." + e.getMessage();
logger.error(msg);
throw new CloudRuntimeException(msg, e);
}
}
private void updateClusterDetails(Connection conn, Map<Long, List<Pair<String, String>>> detailsMap) {
// Insert cluster details into cloud.cluster_details table for existing VMware clusters
// Input parameter detailMap is a map of clusterId and list of key value pairs for that cluster
Long clusterId;
String key;
String val;
List<Pair<String, String>> keyValues;
try {
Iterator<Long> clusterIt = detailsMap.keySet().iterator();
while (clusterIt.hasNext()) {
clusterId = clusterIt.next();
keyValues = detailsMap.get(clusterId);
try( PreparedStatement clusterDetailsInsert = conn.prepareStatement("INSERT INTO `cloud`.`cluster_details` (cluster_id, name, value) VALUES (?, ?, ?)");) {
for (Pair<String, String> keyValuePair : keyValues) {
key = keyValuePair.first();
val = keyValuePair.second();
clusterDetailsInsert.setLong(1, clusterId);
clusterDetailsInsert.setString(2, key);
clusterDetailsInsert.setString(3, val);
clusterDetailsInsert.executeUpdate();
}
logger.debug("Inserted vswitch configuration details into cloud.cluster_details for cluster with id " + clusterId + ".");
}catch (SQLException e) {
throw new CloudRuntimeException("Unable insert cluster details into cloud.cluster_details table.", e);
}
}
} catch (RuntimeException e) {
throw new CloudRuntimeException("Unable insert cluster details into cloud.cluster_details table.", e);
}
}
private String getConfigurationParameter(Connection conn, String category, String paramName) {
try (PreparedStatement pstmt =
conn.prepareStatement("select value from `cloud`.`configuration` where category=? and value is not NULL and name = ?;");)
{
pstmt.setString(1, category);
pstmt.setString(2, paramName);
try(ResultSet rs = pstmt.executeQuery();) {
while (rs.next()) {
return rs.getString("value");
}
}catch (SQLException e) {
throw new CloudRuntimeException("Unable read global configuration parameter " + paramName + ". ", e);
}
} catch (SQLException e) {
throw new CloudRuntimeException("Unable read global configuration parameter " + paramName + ". ", e);
}
return "false";
}
private void setConfigurationParameter(Connection conn, String category, String paramName, String paramVal) {
try (PreparedStatement pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = ? WHERE name = ?;");)
{
pstmt.setString(1, paramVal);
pstmt.setString(2, paramName);
logger.debug("Updating global configuration parameter " + paramName + " with value " + paramVal + ". Update SQL statement is " + pstmt);
pstmt.executeUpdate();
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to set global configuration parameter " + paramName + " to " + paramVal + ". ", e);
}
}
private void movePrivateZoneToDedicatedResource(Connection conn) {
String domainName = "";
try (PreparedStatement sel_dc_dom_id = conn.prepareStatement("SELECT distinct(`domain_id`) FROM `cloud`.`data_center` WHERE `domain_id` IS NOT NULL AND removed IS NULL");) {
try (ResultSet rs3 = sel_dc_dom_id.executeQuery();) {
while (rs3.next()) {
long domainId = rs3.getLong(1);
long affinityGroupId = 0;
// create or find an affinity group for this domain of type
// 'ExplicitDedication'
try (PreparedStatement sel_aff_grp_pstmt =
conn.prepareStatement("SELECT affinity_group.id FROM `cloud`.`affinity_group` INNER JOIN `cloud`.`affinity_group_domain_map` ON affinity_group.id=affinity_group_domain_map.affinity_group_id WHERE affinity_group.type = 'ExplicitDedication' AND affinity_group.acl_type = 'Domain' AND (affinity_group_domain_map.domain_id = ?)");) {
sel_aff_grp_pstmt.setLong(1, domainId);
try (ResultSet rs2 = sel_aff_grp_pstmt.executeQuery();) {
if (rs2.next()) {
// group exists, use it
affinityGroupId = rs2.getLong(1);
} else {
// create new group
try (PreparedStatement sel_dom_id_pstmt = conn.prepareStatement("SELECT name FROM `cloud`.`domain` where id = ?");) {
sel_dom_id_pstmt.setLong(1, domainId);
try (ResultSet sel_dom_id_res = sel_dom_id_pstmt.executeQuery();) {
if (sel_dom_id_res.next()) {
domainName = sel_dom_id_res.getString(1);
}
}
} catch (SQLException e) {
throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e);
}
// create new domain level group for this domain
String type = "ExplicitDedication";
String uuid = UUID.randomUUID().toString();
String groupName = "DedicatedGrp-domain-" + domainName;
logger.debug("Adding AffinityGroup of type " + type + " for domain id " + domainId);
String sql =
"INSERT INTO `cloud`.`affinity_group` (`name`, `type`, `uuid`, `description`, `domain_id`, `account_id`, `acl_type`) VALUES (?, ?, ?, ?, 1, 1, 'Domain')";
try (PreparedStatement insert_pstmt = conn.prepareStatement(sql);) {
insert_pstmt.setString(1, groupName);
insert_pstmt.setString(2, type);
insert_pstmt.setString(3, uuid);
insert_pstmt.setString(4, "dedicated resources group");
insert_pstmt.executeUpdate();
try (PreparedStatement sel_aff_pstmt = conn.prepareStatement("SELECT affinity_group.id FROM `cloud`.`affinity_group` where uuid = ?");) {
sel_aff_pstmt.setString(1, uuid);
try (ResultSet sel_aff_res = sel_aff_pstmt.executeQuery();) {
if (sel_aff_res.next()) {
affinityGroupId = sel_aff_res.getLong(1);
}
} catch (SQLException e) {
throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e);
}
} catch (SQLException e) {
throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e);
}
} catch (SQLException e) {
throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e);
}
// add the domain map
String sqlMap = "INSERT INTO `cloud`.`affinity_group_domain_map` (`domain_id`, `affinity_group_id`) VALUES (?, ?)";
try (PreparedStatement pstmtUpdate = conn.prepareStatement(sqlMap);) {
pstmtUpdate.setLong(1, domainId);
pstmtUpdate.setLong(2, affinityGroupId);
pstmtUpdate.executeUpdate();
} catch (SQLException e) {
throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e);
}
}
} catch (SQLException e) {
throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e);
}
} catch (SQLException e) {
throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e);
}
try (PreparedStatement sel_pstmt = conn.prepareStatement("SELECT `id` FROM `cloud`.`data_center` WHERE `domain_id` = ? AND removed IS NULL");) {
sel_pstmt.setLong(1, domainId);
try (ResultSet sel_pstmt_rs = sel_pstmt.executeQuery();) {
while (sel_pstmt_rs.next()) {
long zoneId = sel_pstmt_rs.getLong(1);
dedicateZone(conn, zoneId, domainId, affinityGroupId);
}
} catch (SQLException e) {
throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e);
}
} catch (SQLException e) {
throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e);
}
}
} catch (SQLException e) {
throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e);
}
}catch (SQLException e) {
throw new CloudRuntimeException("Exception while Moving private zone information to dedicated resources", e);
}
}
private void dedicateZone(Connection conn, long zoneId, long domainId, long affinityGroupId) {
try( PreparedStatement pstmtUpdate2 = conn.prepareStatement("INSERT INTO `cloud`.`dedicated_resources` (`uuid`,`data_center_id`, `domain_id`, `affinity_group_id`) VALUES (?, ?, ?, ?)");) {
// create the dedicated resources entry
pstmtUpdate2.setString(1, UUID.randomUUID().toString());
pstmtUpdate2.setLong(2, zoneId);
pstmtUpdate2.setLong(3, domainId);
pstmtUpdate2.setLong(4, affinityGroupId);
pstmtUpdate2.executeUpdate();
pstmtUpdate2.close();
} catch (SQLException e) {
throw new CloudRuntimeException("Exception while saving zone to dedicated resources", e);
}
}
private void fixBaremetalForeignKeys(Connection conn) {
List<String> keys = new ArrayList<String>();
keys.add("fk_external_dhcp_devices_nsp_id");
keys.add("fk_external_dhcp_devices_host_id");
keys.add("fk_external_dhcp_devices_pod_id");
keys.add("fk_external_dhcp_devices_physical_network_id");
DbUpgradeUtils.dropKeysIfExist(conn, "baremetal_dhcp_devices", keys, true);
keys.add("fk_external_pxe_devices_nsp_id");
keys.add("fk_external_pxe_devices_host_id");
keys.add("fk_external_pxe_devices_physical_network_id");
DbUpgradeUtils.dropKeysIfExist(conn, "baremetal_pxe_devices", keys, true);
try (PreparedStatement alter_pstmt = conn.prepareStatement("ALTER TABLE `cloud`.`baremetal_dhcp_devices` ADD CONSTRAINT `fk_external_dhcp_devices_nsp_id` FOREIGN KEY (`nsp_id`) REFERENCES `physical_network_service_providers` (`id`) ON DELETE CASCADE");)
{
alter_pstmt.executeUpdate();
try(PreparedStatement alter_pstmt_id =
conn.prepareStatement("ALTER TABLE `cloud`.`baremetal_dhcp_devices` ADD CONSTRAINT `fk_external_dhcp_devices_host_id` FOREIGN KEY (`host_id`) REFERENCES `host`(`id`) ON DELETE CASCADE");
) {
alter_pstmt_id.executeUpdate();
try(PreparedStatement alter_pstmt_phy_net =
conn.prepareStatement("ALTER TABLE `cloud`.`baremetal_dhcp_devices` ADD CONSTRAINT `fk_external_dhcp_devices_physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE");)
{
alter_pstmt_phy_net.executeUpdate();
}catch (SQLException e) {
throw new CloudRuntimeException("Unable to add foreign keys to baremetal_dhcp_devices table", e);
}
}catch (SQLException e) {
throw new CloudRuntimeException("Unable to add foreign keys to baremetal_dhcp_devices table", e);
}
logger.debug("Added foreign keys for table baremetal_dhcp_devices");
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to add foreign keys to baremetal_dhcp_devices table", e);
}
try (PreparedStatement alter_pxe_pstmt =
conn.prepareStatement("ALTER TABLE `cloud`.`baremetal_pxe_devices` ADD CONSTRAINT `fk_external_pxe_devices_nsp_id` FOREIGN KEY (`nsp_id`) REFERENCES `physical_network_service_providers` (`id`) ON DELETE CASCADE");)
{
alter_pxe_pstmt.executeUpdate();
try(PreparedStatement alter_pxe_id_pstmt =
conn.prepareStatement("ALTER TABLE `cloud`.`baremetal_pxe_devices` ADD CONSTRAINT `fk_external_pxe_devices_host_id` FOREIGN KEY (`host_id`) REFERENCES `host`(`id`) ON DELETE CASCADE");) {
alter_pxe_id_pstmt.executeUpdate();
try(PreparedStatement alter_pxe_phy_net_pstmt =
conn.prepareStatement("ALTER TABLE `cloud`.`baremetal_pxe_devices` ADD CONSTRAINT `fk_external_pxe_devices_physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE");) {
alter_pxe_phy_net_pstmt.executeUpdate();
}catch (SQLException e) {
throw new CloudRuntimeException("Unable to add foreign keys to baremetal_pxe_devices table", e);
}
}catch (SQLException e) {
throw new CloudRuntimeException("Unable to add foreign keys to baremetal_pxe_devices table", e);
}
logger.debug("Added foreign keys for table baremetal_pxe_devices");
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to add foreign keys to baremetal_pxe_devices table", e);
}
}
private void addIndexForAlert(Connection conn) {
//First drop if it exists. (Due to patches shipped to customers some will have the index and some won't.)
List<String> indexList = new ArrayList<String>();
logger.debug("Dropping index i_alert__last_sent if it exists");
indexList.add("last_sent"); // in 4.1, we created this index that is not in convention.
indexList.add("i_alert__last_sent");
DbUpgradeUtils.dropKeysIfExist(conn, "alert", indexList, false);
//Now add index.
try(PreparedStatement pstmt = conn.prepareStatement("ALTER TABLE `cloud`.`alert` ADD INDEX `i_alert__last_sent`(`last_sent`)");)
{
pstmt.executeUpdate();
logger.debug("Added index i_alert__last_sent for table alert");
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to add index i_alert__last_sent to alert table for the column last_sent", e);
}
}
private void dropUploadTable(Connection conn) {
try(PreparedStatement pstmt0 = conn.prepareStatement("SELECT url, created, type_id, host_id from upload where type=?");) {
// Read upload table - Templates
logger.debug("Populating template_store_ref table");
pstmt0.setString(1, "TEMPLATE");
try(ResultSet rs0 = pstmt0.executeQuery();)
{
try(PreparedStatement pstmt1 = conn.prepareStatement("UPDATE template_store_ref SET download_url=?, download_url_created=? where template_id=? and store_id=?");) {
//Update template_store_ref
while (rs0.next()) {
pstmt1.setString(1, rs0.getString("url"));
pstmt1.setDate(2, rs0.getDate("created"));
pstmt1.setLong(3, rs0.getLong("type_id"));
pstmt1.setLong(4, rs0.getLong("host_id"));
pstmt1.executeUpdate();
}
// Read upload table - Volumes
logger.debug("Populating volume store ref table");
try(PreparedStatement pstmt2 = conn.prepareStatement("SELECT url, created, type_id, host_id, install_path from upload where type=?");) {
pstmt2.setString(1, "VOLUME");
try(ResultSet rs2 = pstmt2.executeQuery();) {
try(PreparedStatement pstmt3 =
conn.prepareStatement("INSERT IGNORE INTO volume_store_ref (volume_id, store_id, zone_id, created, state, download_url, download_url_created, install_path) VALUES (?,?,?,?,?,?,?,?)");) {
//insert into template_store_ref
while (rs2.next()) {
pstmt3.setLong(1, rs2.getLong("type_id"));
pstmt3.setLong(2, rs2.getLong("host_id"));
pstmt3.setLong(3, 1l);// ???
pstmt3.setDate(4, rs2.getDate("created"));
pstmt3.setString(5, "Ready");
pstmt3.setString(6, rs2.getString("url"));
pstmt3.setDate(7, rs2.getDate("created"));
pstmt3.setString(8, rs2.getString("install_path"));
pstmt3.executeUpdate();
}
}catch (SQLException e) {
throw new CloudRuntimeException("Unable add date into template/volume store ref from upload table.", e);
}
}catch (SQLException e) {
throw new CloudRuntimeException("Unable add date into template/volume store ref from upload table.", e);
}
}catch (SQLException e) {
throw new CloudRuntimeException("Unable add date into template/volume store ref from upload table.", e);
}
}catch (SQLException e) {
throw new CloudRuntimeException("Unable add date into template/volume store ref from upload table.", e);
}
}catch (SQLException e) {
throw new CloudRuntimeException("Unable add date into template/volume store ref from upload table.", e);
}
} catch (SQLException e) {
throw new CloudRuntimeException("Unable add date into template/volume store ref from upload table.", e);
}
}
//KVM snapshot flag: only turn on if Customers is using snapshot;
private void setKVMSnapshotFlag(Connection conn) {
logger.debug("Verify and set the KVM snapshot flag if snapshot was used. ");
try(PreparedStatement pstmt = conn.prepareStatement("select count(*) from `cloud`.`snapshots` where hypervisor_type = 'KVM'");)
{
int numRows = 0;
try(ResultSet rs = pstmt.executeQuery();) {
if (rs.next()) {
numRows = rs.getInt(1);
}
if (numRows > 0) {
//Add the configuration flag
try(PreparedStatement update_pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = ? WHERE name = 'kvm.snapshot.enabled'");) {
update_pstmt.setString(1, "true");
update_pstmt.executeUpdate();
}catch (SQLException e) {
throw new CloudRuntimeException("Failed to read the snapshot table for KVM upgrade. ", e);
}
}
}catch (SQLException e) {
throw new CloudRuntimeException("Failed to read the snapshot table for KVM upgrade. ", e);
}
} catch (SQLException e) {
throw new CloudRuntimeException("Failed to read the snapshot table for KVM upgrade. ", e);
}
logger.debug("Done set KVM snapshot flag. ");
}
private void updatePrimaryStore(Connection conn) {
try(PreparedStatement sql = conn.prepareStatement("update storage_pool set storage_provider_name = ? , scope = ? where pool_type = 'Filesystem' or pool_type = 'LVM'");) {
sql.setString(1, DataStoreProvider.DEFAULT_PRIMARY);
sql.setString(2, "HOST");
sql.executeUpdate();
try(PreparedStatement sql2 = conn.prepareStatement("update storage_pool set storage_provider_name = ? , scope = ? where pool_type != 'Filesystem' and pool_type != 'LVM'");) {
sql2.setString(1, DataStoreProvider.DEFAULT_PRIMARY);
sql2.setString(2, "CLUSTER");
sql2.executeUpdate();
}catch (SQLException e) {
throw new CloudRuntimeException("Failed to upgrade vm template data store uuid: " + e.toString());
}
} catch (SQLException e) {
throw new CloudRuntimeException("Failed to upgrade vm template data store uuid: " + e.toString());
}
}
//update the cluster_details table with default overcommit ratios.
private void updateOverCommitRatioClusterDetails(Connection conn) {
try (
PreparedStatement pstmt = conn.prepareStatement("select id, hypervisor_type from `cloud`.`cluster` WHERE removed IS NULL");
PreparedStatement pstmt1 = conn.prepareStatement("INSERT INTO `cloud`.`cluster_details` (cluster_id, name, value) VALUES(?, 'cpuOvercommitRatio', ?)");
PreparedStatement pstmt2 = conn.prepareStatement("INSERT INTO `cloud`.`cluster_details` (cluster_id, name, value) VALUES(?, 'memoryOvercommitRatio', ?)");
PreparedStatement pstmt3 = conn.prepareStatement("select value from `cloud`.`configuration` where name=?");) {
String global_cpu_overprovisioning_factor = "1";
String global_mem_overprovisioning_factor = "1";
pstmt3.setString(1, "cpu.overprovisioning.factor");
try (ResultSet rscpu_global = pstmt3.executeQuery();) {
if (rscpu_global.next())
global_cpu_overprovisioning_factor = rscpu_global.getString(1);
}
pstmt3.setString(1, "mem.overprovisioning.factor");
try (ResultSet rsmem_global = pstmt3.executeQuery();) {
if (rsmem_global.next())
global_mem_overprovisioning_factor = rsmem_global.getString(1);
}
try (ResultSet rs1 = pstmt.executeQuery();) {
while (rs1.next()) {
long id = rs1.getLong(1);
String hypervisor_type = rs1.getString(2);
if (HypervisorType.VMware.toString().equalsIgnoreCase(hypervisor_type)) {
pstmt1.setLong(1, id);
pstmt1.setString(2, global_cpu_overprovisioning_factor);
pstmt1.execute();
pstmt2.setLong(1, id);
pstmt2.setString(2, global_mem_overprovisioning_factor);
pstmt2.execute();
} else {
//update cluster_details table with the default overcommit ratios.
pstmt1.setLong(1, id);
pstmt1.setString(2, global_cpu_overprovisioning_factor);
pstmt1.execute();
pstmt2.setLong(1, id);
pstmt2.setString(2, "1");
pstmt2.execute();
}
}
}
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to update cluster_details with default overcommit ratios.", e);
}
}
@Override
public InputStream[] getCleanupScripts() {
final String scriptFile = "META-INF/db/schema-410to420-cleanup.sql";
final InputStream script = Thread.currentThread().getContextClassLoader().getResourceAsStream(scriptFile);
if (script == null) {
throw new CloudRuntimeException("Unable to find " + scriptFile);
}
return new InputStream[] {script};
}
private String getNewLabel(ResultSet rs, String oldParamValue) {
int separatorIndex;
String oldGuestLabel;
String newGuestLabel = oldParamValue;
try {
// No need to iterate because the global param setting applies to all physical networks irrespective of traffic type
if ((rs != null) && (rs.next())) {
oldGuestLabel = rs.getString("vmware_network_label");
// guestLabel is in format [[<VSWITCHNAME>],VLANID]
separatorIndex = oldGuestLabel.indexOf(",");
if (separatorIndex > -1) {
newGuestLabel += oldGuestLabel.substring(separatorIndex);
}
}
} catch (SQLException e) {
logger.error(new CloudRuntimeException("Failed to read vmware_network_label : " + e));
}
return newGuestLabel;
}
private void upgradeVmwareLabels(Connection conn) {
String newLabel;
String trafficType = null;
String trafficTypeVswitchParam;
String trafficTypeVswitchParamValue;
try (PreparedStatement pstmt =
conn.prepareStatement("select name,value from `cloud`.`configuration` where category='Hidden' and value is not NULL and name REGEXP 'vmware*.vswitch';");)
{
// update the existing vmware traffic labels
try(ResultSet rsParams = pstmt.executeQuery();) {
while (rsParams.next()) {
trafficTypeVswitchParam = rsParams.getString("name");
trafficTypeVswitchParamValue = rsParams.getString("value");
// When upgraded from 4.0 to 4.1 update physical network traffic label with trafficTypeVswitchParam
if (trafficTypeVswitchParam.equals("vmware.private.vswitch")) {
trafficType = "Management"; //TODO(sateesh): Ignore storage traffic, as required physical network already implemented, anything else tobe done?
} else if (trafficTypeVswitchParam.equals("vmware.public.vswitch")) {
trafficType = "Public";
} else if (trafficTypeVswitchParam.equals("vmware.guest.vswitch")) {
trafficType = "Guest";
}
try(PreparedStatement sel_pstmt =
conn.prepareStatement("select physical_network_id, traffic_type, vmware_network_label from physical_network_traffic_types where vmware_network_label is not NULL and traffic_type=?;");) {
pstmt.setString(1, trafficType);
try(ResultSet rsLabel = sel_pstmt.executeQuery();) {
newLabel = getNewLabel(rsLabel, trafficTypeVswitchParamValue);
try(PreparedStatement update_pstmt =
conn.prepareStatement("update physical_network_traffic_types set vmware_network_label = ? where traffic_type = ? and vmware_network_label is not NULL;");) {
logger.debug("Updating vmware label for " + trafficType + " traffic. Update SQL statement is " + pstmt);
pstmt.setString(1, newLabel);
pstmt.setString(2, trafficType);
update_pstmt.executeUpdate();
}catch (SQLException e) {
throw new CloudRuntimeException("Unable to set vmware traffic labels ", e);
}
}catch (SQLException e) {
throw new CloudRuntimeException("Unable to set vmware traffic labels ", e);
}
}catch (SQLException e) {
throw new CloudRuntimeException("Unable to set vmware traffic labels ", e);
}
}
}catch (SQLException e) {
throw new CloudRuntimeException("Unable to set vmware traffic labels ", e);
}
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to set vmware traffic labels ", e);
}
}
private void persistLegacyZones(Connection conn) {
List<Long> listOfLegacyZones = new ArrayList<Long>();
List<Long> listOfNonLegacyZones = new ArrayList<Long>();
Map<String, ArrayList<Long>> dcToZoneMap = new HashMap<String, ArrayList<Long>>();
ResultSet clusters = null;
Long zoneId;
Long clusterId;
ArrayList<String> dcList = null;
String clusterHypervisorType;
boolean legacyZone;
boolean ignoreZone;
Long count;
String dcOfPreviousCluster = null;
String dcOfCurrentCluster = null;
String[] tokens;
String url;
String vc = "";
String dcName = "";
try (PreparedStatement pstmt = conn.prepareStatement("select id from `cloud`.`data_center` where removed is NULL");) {
try (ResultSet rs = pstmt.executeQuery();) {
while (rs.next()) {
zoneId = rs.getLong("id");
try (PreparedStatement clustersQuery = conn.prepareStatement("select id, hypervisor_type from `cloud`.`cluster` where removed is NULL AND data_center_id=?");) {
clustersQuery.setLong(1, zoneId);
legacyZone = false;
ignoreZone = true;
dcList = new ArrayList<String>();
count = 0L;
// Legacy zone term is meant only for VMware
// Legacy zone is a zone with at least 2 clusters & with multiple DCs or VCs
clusters = clustersQuery.executeQuery();
if (!clusters.next()) {
continue; // Ignore the zone without any clusters
} else {
dcOfPreviousCluster = null;
dcOfCurrentCluster = null;
do {
clusterHypervisorType = clusters.getString("hypervisor_type");
clusterId = clusters.getLong("id");
if (clusterHypervisorType.equalsIgnoreCase("VMware")) {
ignoreZone = false;
try (PreparedStatement clusterDetailsQuery = conn
.prepareStatement("select value from `cloud`.`cluster_details` where name='url' and cluster_id=?");) {
clusterDetailsQuery.setLong(1, clusterId);
try (ResultSet clusterDetails = clusterDetailsQuery.executeQuery();) {
clusterDetails.next();
url = clusterDetails.getString("value");
tokens = url.split("/"); // url format - http://vcenter/dc/cluster
vc = tokens[2];
dcName = tokens[3];
dcOfPreviousCluster = dcOfCurrentCluster;
dcOfCurrentCluster = dcName + "@" + vc;
if (!dcList.contains(dcOfCurrentCluster)) {
dcList.add(dcOfCurrentCluster);
}
if (count > 0) {
if (!dcOfPreviousCluster.equalsIgnoreCase(dcOfCurrentCluster)) {
legacyZone = true;
logger.debug("Marking the zone " + zoneId + " as legacy zone.");
}
}
} catch (SQLException e) {
throw new CloudRuntimeException("Unable add zones to cloud.legacyzones table.", e);
}
} catch (SQLException e) {
throw new CloudRuntimeException("Unable add zones to cloud.legacyzones table.", e);
}
} else {
logger.debug("Ignoring zone " + zoneId + " with hypervisor type " + clusterHypervisorType);
break;
}
count++;
} while (clusters.next());
if (ignoreZone) {
continue; // Ignore the zone with hypervisors other than VMware
}
}
} catch (SQLException e) {
throw new CloudRuntimeException("persistLegacyZones:Exception:" + e.getMessage(), e);
}
if (legacyZone) {
listOfLegacyZones.add(zoneId);
} else {
listOfNonLegacyZones.add(zoneId);
}
for (String dc : dcList) {
ArrayList<Long> dcZones = new ArrayList<Long>();
if (dcToZoneMap.get(dc) != null) {
dcZones = dcToZoneMap.get(dc);
}
dcZones.add(zoneId);
dcToZoneMap.put(dc, dcZones);
}
}
// If a VMware datacenter in a vCenter maps to more than 1 CloudStack zone, mark all the zones it is mapped to as legacy
for (Map.Entry<String, ArrayList<Long>> entry : dcToZoneMap.entrySet()) {
if (entry.getValue().size() > 1) {
for (Long newLegacyZone : entry.getValue()) {
if (listOfNonLegacyZones.contains(newLegacyZone)) {
listOfNonLegacyZones.remove(newLegacyZone);
listOfLegacyZones.add(newLegacyZone);
}
}
}
}
updateLegacyZones(conn, listOfLegacyZones);
updateNonLegacyZones(conn, listOfNonLegacyZones);
} catch (SQLException e) {
logger.error("Unable to discover legacy zones." + e.getMessage(),e);
throw new CloudRuntimeException("Unable to discover legacy zones." + e.getMessage(), e);
}
}catch (SQLException e) {
logger.error("Unable to discover legacy zones." + e.getMessage(),e);
throw new CloudRuntimeException("Unable to discover legacy zones." + e.getMessage(), e);
}
}
private void updateLegacyZones(Connection conn, List<Long> zones) {
//Insert legacy zones into table for legacy zones.
try (PreparedStatement legacyZonesQuery = conn.prepareStatement("INSERT INTO `cloud`.`legacy_zones` (zone_id) VALUES (?)");){
for (Long zoneId : zones) {
legacyZonesQuery.setLong(1, zoneId);
legacyZonesQuery.executeUpdate();
logger.debug("Inserted zone " + zoneId + " into cloud.legacyzones table");
}
} catch (SQLException e) {
throw new CloudRuntimeException("Unable add zones to cloud.legacyzones table.", e);
}
}
private void updateNonLegacyZones(Connection conn, List<Long> zones) {
try {
for (Long zoneId : zones) {
logger.debug("Discovered non-legacy zone " + zoneId + ". Processing the zone to associate with VMware datacenter.");
// All clusters in a non legacy zone will belong to the same VMware DC, hence pick the first cluster
try (PreparedStatement clustersQuery = conn.prepareStatement("select id from `cloud`.`cluster` where removed is NULL AND data_center_id=?");) {
clustersQuery.setLong(1, zoneId);
try (ResultSet clusters = clustersQuery.executeQuery();) {
clusters.next();
Long clusterId = clusters.getLong("id");
// Get VMware datacenter details from cluster_details table
String user = null;
String password = null;
String url = null;
try (PreparedStatement clusterDetailsQuery = conn.prepareStatement("select name, value from `cloud`.`cluster_details` where cluster_id=?");) {
clusterDetailsQuery.setLong(1, clusterId);
try (ResultSet clusterDetails = clusterDetailsQuery.executeQuery();) {
while (clusterDetails.next()) {
String key = clusterDetails.getString(1);
String value = clusterDetails.getString(2);
if (key.equalsIgnoreCase("username")) {
user = value;
} else if (key.equalsIgnoreCase("password")) {
password = value;
} else if (key.equalsIgnoreCase("url")) {
url = value;
}
}
String[] tokens = url.split("/"); // url format - http://vcenter/dc/cluster
String vc = tokens[2];
String dcName = tokens[3];
String guid = dcName + "@" + vc;
try (PreparedStatement insertVmWareDC = conn
.prepareStatement("INSERT INTO `cloud`.`vmware_data_center` (uuid, name, guid, vcenter_host, username, password) values(?, ?, ?, ?, ?, ?)");) {
insertVmWareDC.setString(1, UUID.randomUUID().toString());
insertVmWareDC.setString(2, dcName);
insertVmWareDC.setString(3, guid);
insertVmWareDC.setString(4, vc);
insertVmWareDC.setString(5, user);
insertVmWareDC.setString(6, password);
insertVmWareDC.executeUpdate();
}
try (PreparedStatement selectVmWareDC = conn.prepareStatement("SELECT id FROM `cloud`.`vmware_data_center` where guid=?");) {
selectVmWareDC.setString(1, guid);
try (ResultSet vmWareDcInfo = selectVmWareDC.executeQuery();) {
Long vmwareDcId = -1L;
if (vmWareDcInfo.next()) {
vmwareDcId = vmWareDcInfo.getLong("id");
}
try (PreparedStatement insertMapping = conn
.prepareStatement("INSERT INTO `cloud`.`vmware_data_center_zone_map` (zone_id, vmware_data_center_id) values(?, ?)");) {
insertMapping.setLong(1, zoneId);
insertMapping.setLong(2, vmwareDcId);
insertMapping.executeUpdate();
}
}
}
}
}
}
}
}
} catch (SQLException e) {
String msg = "Unable to update non legacy zones." + e.getMessage();
logger.error(msg);
throw new CloudRuntimeException(msg, e);
}
}
private void createPlaceHolderNics(Connection conn) {
try (PreparedStatement pstmt =
conn.prepareStatement("SELECT network_id, gateway, ip4_address FROM `cloud`.`nics` WHERE reserver_name IN ('DirectNetworkGuru','DirectPodBasedNetworkGuru') and vm_type='DomainRouter' AND removed IS null");)
{
try(ResultSet rs = pstmt.executeQuery();) {
while (rs.next()) {
Long networkId = rs.getLong(1);
String gateway = rs.getString(2);
String ip = rs.getString(3);
String uuid = UUID.randomUUID().toString();
//Insert placeholder nic for each Domain router nic in Shared network
try(PreparedStatement insert_pstmt =
conn.prepareStatement("INSERT INTO `cloud`.`nics` (uuid, ip4_address, gateway, network_id, state, strategy, vm_type, default_nic, created) VALUES (?, ?, ?, ?, 'Reserved', 'PlaceHolder', 'DomainRouter', 0, now())");) {
insert_pstmt.setString(1, uuid);
insert_pstmt.setString(2, ip);
insert_pstmt.setString(3, gateway);
insert_pstmt.setLong(4, networkId);
insert_pstmt.executeUpdate();
}catch (SQLException e) {
throw new CloudRuntimeException("Unable to create placeholder nics", e);
}
logger.debug("Created placeholder nic for the ipAddress " + ip + " and network " + networkId);
}
}catch (SQLException e) {
throw new CloudRuntimeException("Unable to create placeholder nics", e);
}
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to create placeholder nics", e);
}
}
private void updateRemoteAccessVpn(Connection conn) {
try(PreparedStatement pstmt = conn.prepareStatement("SELECT vpn_server_addr_id FROM `cloud`.`remote_access_vpn`");) {
try(ResultSet rs = pstmt.executeQuery();) {
long id = 1;
while (rs.next()) {
String uuid = UUID.randomUUID().toString();
Long ipId = rs.getLong(1);
try(PreparedStatement update_pstmt = conn.prepareStatement("UPDATE `cloud`.`remote_access_vpn` set uuid=?, id=? where vpn_server_addr_id=?");) {
update_pstmt.setString(1, uuid);
update_pstmt.setLong(2, id);
update_pstmt.setLong(3, ipId);
update_pstmt.executeUpdate();
id++;
}catch (SQLException e) {
throw new CloudRuntimeException("Unable to update id/uuid of remote_access_vpn table", e);
}
}
}catch (SQLException e) {
throw new CloudRuntimeException("Unable to update id/uuid of remote_access_vpn table", e);
}
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to update id/uuid of remote_access_vpn table", e);
}
}
private void addEgressFwRulesForSRXGuestNw(Connection conn) {
ResultSet rs = null;
try(PreparedStatement pstmt = conn.prepareStatement("select network_id FROM `cloud`.`ntwk_service_map` where service='Firewall' and provider='JuniperSRX' ");) {
rs = pstmt.executeQuery();
while (rs.next()) {
long netId = rs.getLong(1);
//checking for Isolated OR Virtual
try(PreparedStatement sel_net_pstmt =
conn.prepareStatement("select account_id, domain_id FROM `cloud`.`networks` where (guest_type='Isolated' OR guest_type='Virtual') and traffic_type='Guest' and vpc_id is NULL and (state='implemented' OR state='Shutdown') and id=? ");) {
sel_net_pstmt.setLong(1, netId);
logger.debug("Getting account_id, domain_id from networks table: ");
try(ResultSet rsNw = pstmt.executeQuery();)
{
if (rsNw.next()) {
long accountId = rsNw.getLong(1);
long domainId = rsNw.getLong(2);
//Add new rule for the existing networks
logger.debug("Adding default egress firewall rule for network " + netId);
try (PreparedStatement insert_pstmt =
conn.prepareStatement("INSERT INTO firewall_rules (uuid, state, protocol, purpose, account_id, domain_id, network_id, xid, created, traffic_type) VALUES (?, 'Active', 'all', 'Firewall', ?, ?, ?, ?, now(), 'Egress')");) {
insert_pstmt.setString(1, UUID.randomUUID().toString());
insert_pstmt.setLong(2, accountId);
insert_pstmt.setLong(3, domainId);
insert_pstmt.setLong(4, netId);
insert_pstmt.setString(5, UUID.randomUUID().toString());
logger.debug("Inserting default egress firewall rule " + insert_pstmt);
insert_pstmt.executeUpdate();
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to set egress firewall rules ", e);
}
try (PreparedStatement sel_firewall_pstmt = conn.prepareStatement("select id from firewall_rules where protocol='all' and network_id=?");) {
sel_firewall_pstmt.setLong(1, netId);
try (ResultSet rsId = sel_firewall_pstmt.executeQuery();) {
long firewallRuleId;
if (rsId.next()) {
firewallRuleId = rsId.getLong(1);
try (PreparedStatement insert_pstmt = conn.prepareStatement("insert into firewall_rules_cidrs (firewall_rule_id,source_cidr) values (?, '0.0.0.0/0')");) {
insert_pstmt.setLong(1, firewallRuleId);
logger.debug("Inserting rule for cidr 0.0.0.0/0 for the new Firewall rule id=" + firewallRuleId + " with statement " + insert_pstmt);
insert_pstmt.executeUpdate();
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to set egress firewall rules ", e);
}
}
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to set egress firewall rules ", e);
}
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to set egress firewall rules ", e);
}