1# coding: utf-8
2
3#-------------------------------------------------------------------------
4# Copyright (c) Microsoft Corporation. All rights reserved.
5# Licensed under the MIT License. See License.txt in the project root for
6# license information.
7#--------------------------------------------------------------------------
8
9
10# TEST SCENARIO COVERAGE
11# ----------------------
12# Methods Total   : 60
13# Methods Covered : 60
14# Examples Total  : 63
15# Examples Tested : 63
16# Coverage %      : 100
17# ----------------------
18
19#  network_watchers:  16/18
20#  network_profiles: 7/7
21#  network_security_groups:  6/6
22#  network_virtual_appliances: 0/6  # TODO: (InvalidResourceType) The resource type could not be found in the namespace 'Microsoft.Network' for api version '2020-03-01'
23#  flow_logs: 3/3
24#  packet_captures: 6/6
25#  connection_monitors: 9/9
26#  security_rules: 4/4
27#  default_security_rules: 2/2
28
29
30import unittest
31
32import azure.mgmt.network
33from azure.core.exceptions import HttpResponseError
34from devtools_testutils import AzureMgmtTestCase, RandomNameResourceGroupPreparer
35
36AZURE_LOCATION = 'eastus'
37
38@unittest.skip("Fix it later.")
39class MgmtNetworkTest(AzureMgmtTestCase):
40
41    def setUp(self):
42        super(MgmtNetworkTest, self).setUp()
43        self.mgmt_client = self.create_mgmt_client(
44            azure.mgmt.network.NetworkManagementClient
45        )
46        self.mgmt_client_v190601 = self.create_mgmt_client(
47            azure.mgmt.network.NetworkManagementClient,
48            api_version="2019-06-01"
49        )
50        if self.is_live:
51            from azure.mgmt.compute import ComputeManagementClient
52            self.compute_client = self.create_mgmt_client(
53                ComputeManagementClient
54            )
55            from azure.mgmt.storage import StorageManagementClient
56            self.storage_client = self.create_mgmt_client(
57                StorageManagementClient
58            )
59
60    def create_virtual_network(self, group_name, location, network_name, subnet_name):
61
62        result = self.mgmt_client.virtual_networks.begin_create_or_update(
63            group_name,
64            network_name,
65            {
66                'location': location,
67                'address_space': {
68                    'address_prefixes': ['10.0.0.0/16']
69                }
70            },
71        )
72        result_create = result.result()
73
74        async_subnet_creation = self.mgmt_client.subnets.begin_create_or_update(
75            group_name,
76            network_name,
77            subnet_name,
78            {'address_prefix': '10.0.0.0/24'}
79        )
80        subnet_info = async_subnet_creation.result()
81
82        return subnet_info
83
84    def create_network_interface(self, group_name, location, nic_name, subnet):
85
86        async_nic_creation = self.mgmt_client.network_interfaces.begin_create_or_update(
87            group_name,
88            nic_name,
89            {
90                'location': location,
91                'ip_configurations': [{
92                    'name': 'MyIpConfig',
93                    'subnet': {
94                        'id': subnet.id
95                    }
96                }]
97            }
98        )
99        nic_info = async_nic_creation.result()
100
101        return nic_info.id
102
103    def get_network_interface(self, group_name, nic_name):
104
105        nic = self.mgmt_client.network_interfaces.get(group_name, nic_name)
106        return nic
107
108    def create_storage_account(self, group_name, location, storage_name):
109        params_create = azure.mgmt.storage.models.StorageAccountCreateParameters(
110            sku=azure.mgmt.storage.models.Sku(name=azure.mgmt.storage.models.SkuName.standard_lrs),
111            kind=azure.mgmt.storage.models.Kind.storage,
112            location=location
113        )
114        result_create = self.storage_client.storage_accounts.begin_create(
115            group_name,
116            storage_name,
117            params_create,
118        )
119        account = result_create.result()
120        return account.id
121
122    def create_virtual_hub(self, location, group_name, virtual_wan_name, virtual_hub_name):
123
124        # VirtualWANCreate[put]
125        BODY = {
126          "location": location,
127          "tags": {
128            "key1": "value1"
129          },
130          "disable_vpn_encryption": False,
131          "type": "Basic"
132        }
133        result = self.mgmt_client.virtual_wans.begin_create_or_update(group_name, virtual_wan_name, BODY)
134        wan = result.result()
135
136        # TODO: something wrong in virtualhub
137        BODY = {
138          "location": location,
139          "tags": {
140            "key1": "value1"
141          },
142          "virtual_wan": {
143            "id": wan.id
144          },
145          "address_prefix": "10.168.0.0/24",
146          "sku": "Basic"
147        }
148        result = self.mgmt_client.virtual_hubs.begin_create_or_update(group_name, virtual_hub_name, BODY)
149        try:
150            result = result.result()
151        except HttpResponseError as e:
152            self.assertEquals(str(e), "(InternalServerError) An error occurred.")
153        return result
154
155    def create_vm(self, group_name, location, vm_name, network_name, subnet_name, interface_name):
156        # create network
157        subnet = self.create_virtual_network(group_name, location, network_name, subnet_name)
158        nic_id = self.create_network_interface(group_name, location, interface_name, subnet)
159
160        # Create a vm with empty data disks.[put]
161        BODY = {
162          "location": "eastus",
163          "hardware_profile": {
164            "vm_size": "Standard_D2_v2"
165          },
166          "storage_profile": {
167            "image_reference": {
168              "sku": "2016-Datacenter",
169              "publisher": "MicrosoftWindowsServer",
170              "version": "latest",
171              "offer": "WindowsServer"
172            },
173            "os_disk": {
174              "caching": "ReadWrite",
175              "managed_disk": {
176                "storage_account_type": "Standard_LRS"
177              },
178              "name": "myVMosdisk",
179              "create_option": "FromImage"
180            },
181            "data_disks": [
182              {
183                "disk_size_gb": "1023",
184                "create_option": "Empty",
185                "lun": "0"
186              },
187              {
188                "disk_size_gb": "1023",
189                "create_option": "Empty",
190                "lun": "1"
191              }
192            ]
193          },
194          "os_profile": {
195            "admin_username": "testuser",
196            "computer_name": "myVM",
197            "admin_password": "Aa1!zyx_",
198            "windows_configuration": {
199              "enable_automatic_updates": True  # need automatic update for reimage
200            }
201          },
202          "network_profile": {
203            "network_interfaces": [
204              {
205                "id": nic_id,
206                "properties": {
207                  "primary": True
208                }
209              }
210            ]
211          }
212        }
213        result = self.compute_client.virtual_machines.begin_create_or_update(group_name, vm_name, BODY)
214        result = result.result()
215
216    def create_vm_extension(self, group_name, location, vm_name, vm_extension_name):
217
218        # Create virtual machine extension
219        BODY = {
220          "location": location,
221          "auto_upgrade_minor_version": True,
222          "publisher": "Microsoft.Azure.NetworkWatcher",
223          "virtual_machine_extension_type": "NetworkWatcherAgentWindows",
224          # "type_properties_type": "NetworkWatcherAgentWindows",
225          "type_handler_version": "1.4",
226        }
227        result = self.compute_client.virtual_machine_extensions.begin_create_or_update(group_name, vm_name, vm_extension_name, BODY)
228        result = result.result()
229
230    def create_public_ip_address(self, group_name, location, public_ip_address_name):
231        # Create public IP address defaults[put]
232        BODY = {
233          "public_ip_allocation_method": "Static",
234          "idle_timeout_in_minutes": 10,
235          "public_ip_address_version": "IPv4",
236          "location": location,
237          "sku": {
238            "name": "Standard"
239          }
240        }
241        result = self.mgmt_client.public_ip_addresses.begin_create_or_update(group_name, public_ip_address_name, BODY)
242        return result.result()
243
244    def create_virtual_network_gateway(self, group_name, location, vn_gateway, network_name, subnet_name, public_ip_address_name, ipconfig_name):
245        # create network
246        subnet = self.create_virtual_network(group_name, location, network_name, subnet_name)
247        public_ip_address = self.create_public_ip_address(group_name, location, public_ip_address_name)
248
249        BODY = {
250          "ip_configurations": [
251            {
252              "private_ip_allocation_method": "Dynamic",
253              "subnet": {
254                # "id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Network/virtualNetworks/" + VIRTUAL_NETWORK_NAME + "/subnets/" + GATEWAY_SUBNET_NAME + ""
255                "id": subnet.id
256              },
257              "public_ip_address": {
258                # "id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Network/publicIPAddresses/" + PUBLIC_IP_ADDRESS_NAME + ""
259                "id": public_ip_address.id
260              },
261              "name": ipconfig_name
262            }
263          ],
264          "gateway_type": "Vpn",
265          "vpn_type": "RouteBased",
266          "enable_bgp": False,
267          "active_active": False,
268          "enable_dns_forwarding": False,
269          "sku": {
270            "name": "VpnGw1",
271            "tier": "VpnGw1"
272          },
273          "bgp_settings": {
274            "asn": "65515",
275            "bgp_peering_address": "10.0.1.30",
276            "peer_weight": "0"
277          },
278          "custom_routes": {
279            "address_prefixes": [
280              "101.168.0.6/32"
281            ]
282          },
283          "location": location
284        }
285        result = self.mgmt_client.virtual_network_gateways.begin_create_or_update(group_name, vn_gateway, BODY)
286        result = result.result()
287
288    @RandomNameResourceGroupPreparer(location=AZURE_LOCATION)
289    def test_network_watcher_troubleshoot(self, resource_group):
290        SUBSCRIPTION_ID = self.settings.SUBSCRIPTION_ID
291        RESOURCE_GROUP = resource_group.name
292
293        NETWORK_WATCHER_NAME = self.get_resource_name("networkwatcher")
294        VIRTUAL_MACHINE_NAME = self.get_resource_name("virtualmachine")
295        VIRTUAL_NETWORK_NAME = self.get_resource_name("virtualnetwork")
296        VIRTUAL_NETWORK_GATEWAY_NAME = self.get_resource_name("virtualnetworkgateway")
297        PUBLIC_IP_ADDRESS_NAME = self.get_resource_name("publicipaddress")
298        SUBNET_NAME = "GatewaySubnet"
299        STORAGE_ACCOUNT_NAME = self.get_resource_name("storagename")
300        IP_CONFIGURATION_NAME = self.get_resource_name("ipconfig")
301
302        if self.is_live:
303            self.create_virtual_network_gateway(
304                RESOURCE_GROUP,
305                AZURE_LOCATION,
306                VIRTUAL_NETWORK_GATEWAY_NAME,
307                VIRTUAL_MACHINE_NAME,
308                SUBNET_NAME,
309                PUBLIC_IP_ADDRESS_NAME,
310                IP_CONFIGURATION_NAME)
311            self.create_storage_account(RESOURCE_GROUP, AZURE_LOCATION, STORAGE_ACCOUNT_NAME)
312
313        # Create network watcher[put]
314        BODY = {
315          "location": "eastus"
316        }
317        result = self.mgmt_client.network_watchers.create_or_update(resource_group.name, NETWORK_WATCHER_NAME, BODY)
318
319        # Get troubleshooting[post]
320        BODY = {
321          "target_resource_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Network/virtualNetworkGateways/" + VIRTUAL_NETWORK_GATEWAY_NAME + "",
322          "storage_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Storage/storageAccounts/" + STORAGE_ACCOUNT_NAME + "",
323          "storage_path": "https://" + STORAGE_ACCOUNT_NAME + ".blob.core.windows.net/troubleshooting"
324        }
325        result = self.mgmt_client.network_watchers.begin_get_troubleshooting(resource_group.name, NETWORK_WATCHER_NAME, BODY)
326        result = result.result()
327
328        # Get troubleshoot result[post]
329        BODY = {
330          "target_resource_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Network/virtualNetworkGateways/" + VIRTUAL_NETWORK_GATEWAY_NAME + ""
331        }
332        result = self.mgmt_client.network_watchers.begin_get_troubleshooting_result(resource_group.name, NETWORK_WATCHER_NAME, BODY)
333        result = result.result()
334
335        # Delete network watcher[delete]
336        result = self.mgmt_client.network_watchers.begin_delete(resource_group.name, NETWORK_WATCHER_NAME)
337        result = result.result()
338
339    @unittest.skip("NsgsNotAppliedOnNic")
340    @RandomNameResourceGroupPreparer(location=AZURE_LOCATION)
341    def test_network_watcher_ip_flow(self, resource_group):
342
343        SUBSCRIPTION_ID = self.settings.SUBSCRIPTION_ID
344        RESOURCE_GROUP = resource_group.name
345        NETWORK_WATCHER_NAME = self.get_resource_name("networkwatcher")
346        VIRTUAL_NETWORK_NAME = self.get_resource_name("virtualnetwork")
347        SUBNET_NAME = self.get_resource_name("subnet")
348        INTERFACE_NAME = self.get_resource_name("interface")
349        VIRTUAL_MACHINE_NAME = self.get_resource_name("virtualmachine")
350        VIRTUAL_MACHINE_EXTENSION_NAME = self.get_resource_name("virtualmachineextension")
351
352        if self.is_live:
353            self.create_vm(RESOURCE_GROUP, AZURE_LOCATION, VIRTUAL_MACHINE_NAME, VIRTUAL_NETWORK_NAME, SUBNET_NAME, INTERFACE_NAME)
354            self.create_vm_extension(RESOURCE_GROUP, AZURE_LOCATION, VIRTUAL_MACHINE_NAME, VIRTUAL_MACHINE_EXTENSION_NAME)
355            nic = self.get_network_interface(RESOURCE_GROUP, INTERFACE_NAME)
356            local_ip_address = nic.ip_configurations[0].private_ip_address
357        else:
358            local_ip_address = '10.0.0.1'
359
360        # Create network watcher[put]
361        BODY = {
362          "location": "eastus"
363        }
364        result = self.mgmt_client.network_watchers.create_or_update(resource_group.name, NETWORK_WATCHER_NAME, BODY)
365
366        # Ip flow verify[post]
367        BODY = {
368          "target_resource_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Compute/virtualMachines/" + VIRTUAL_MACHINE_NAME + "",
369          "direction": "Outbound",
370          "protocol": "TCP",
371          "local_port": "80",
372          "remote_port": "80",
373          "local_ip_address": local_ip_address,
374          "remote_ip_address": "121.10.1.1"
375        }
376        result = self.mgmt_client.network_watchers.begin_verify_ip_flow(resource_group.name, NETWORK_WATCHER_NAME, BODY)
377        result = result.result()
378
379        # Delete network watcher[delete]
380        result = self.mgmt_client.network_watchers.begin_delete(resource_group.name, NETWORK_WATCHER_NAME)
381        result = result.result()
382
383    @RandomNameResourceGroupPreparer(location=AZURE_LOCATION)
384    def test_network_watcher_flow_log(self, resource_group):
385        SUBSCRIPTION_ID = self.settings.SUBSCRIPTION_ID
386        RESOURCE_GROUP = resource_group.name
387
388        NETWORK_WATCHER_NAME = self.get_resource_name("networkwatcher")
389        VIRTUAL_MACHINE_NAME = self.get_resource_name("virtualmachine")
390        VIRTUAL_NETWORK_NAME = self.get_resource_name("virtualnetwork")
391        VIRTUAL_NETWORK_GATEWAY_NAME = self.get_resource_name("virtualnetworkgateway")
392        PUBLIC_IP_ADDRESS_NAME = self.get_resource_name("publicipaddress")
393        SUBNET_NAME = "GatewaySubnet"
394        STORAGE_ACCOUNT_NAME = self.get_resource_name("storagename")
395        IP_CONFIGURATION_NAME = self.get_resource_name("ipconfig")
396        FLOW_LOG_NAME = self.get_resource_name("floglog")
397        NETWORK_SECURITY_GROUP_NAME = self.get_resource_name("networksecuritygroup")
398
399        if self.is_live:
400            self.create_virtual_network_gateway(
401                RESOURCE_GROUP,
402                AZURE_LOCATION,
403                VIRTUAL_NETWORK_GATEWAY_NAME,
404                VIRTUAL_MACHINE_NAME,
405                SUBNET_NAME,
406                PUBLIC_IP_ADDRESS_NAME,
407                IP_CONFIGURATION_NAME)
408            self.create_storage_account(RESOURCE_GROUP, AZURE_LOCATION, STORAGE_ACCOUNT_NAME)
409
410        # Create network watcher[put]
411        BODY = {
412          "location": "eastus"
413        }
414        result = self.mgmt_client.network_watchers.create_or_update(resource_group.name, NETWORK_WATCHER_NAME, BODY)
415
416        # Create network security group[put]
417        BODY = {
418          "location": "eastus"
419        }
420        result = self.mgmt_client.network_security_groups.begin_create_or_update(resource_group.name, NETWORK_SECURITY_GROUP_NAME, BODY)
421        result = result.result()
422
423        # Create or update flow log[put]
424        BODY = {
425          "location": AZURE_LOCATION,
426          "target_resource_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Network/networkSecurityGroups/" + NETWORK_SECURITY_GROUP_NAME + "",
427          "storage_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Storage/storageAccounts/" + STORAGE_ACCOUNT_NAME + "",
428          "enabled": True,
429          "format": {
430            "type": "JSON",
431            "version": "1"
432          }
433        }
434        result = self.mgmt_client.flow_logs.begin_create_or_update(resource_group.name, NETWORK_WATCHER_NAME, FLOW_LOG_NAME, BODY)
435        result = result.result()
436
437        # Get flow log[get]
438        result = self.mgmt_client.flow_logs.get(resource_group.name, NETWORK_WATCHER_NAME, FLOW_LOG_NAME)
439
440         # Get flow log status[post]
441        BODY = {
442          "target_resource_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Network/networkSecurityGroups/" + NETWORK_SECURITY_GROUP_NAME + ""
443        }
444        result = self.mgmt_client.network_watchers.begin_get_flow_log_status(resource_group.name, NETWORK_WATCHER_NAME, BODY)
445        result = result.result()
446
447        # Configure flow log[post]
448        BODY = {
449          "target_resource_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Network/networkSecurityGroups/" + NETWORK_SECURITY_GROUP_NAME + "",
450          "storage_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Storage/storageAccounts/" + STORAGE_ACCOUNT_NAME + "",
451          "enabled": True
452        }
453        result = self.mgmt_client.network_watchers.begin_set_flow_log_configuration(resource_group.name, NETWORK_WATCHER_NAME, BODY)
454        result = result.result()
455
456        # Delete flow log[delete]
457        result = self.mgmt_client.flow_logs.begin_delete(resource_group.name, NETWORK_WATCHER_NAME, FLOW_LOG_NAME)
458        result = result.result()
459
460        # Delete network watcher[delete]
461        result = self.mgmt_client.network_watchers.begin_delete(resource_group.name, NETWORK_WATCHER_NAME)
462        result = result.result()
463
464    @RandomNameResourceGroupPreparer(location=AZURE_LOCATION)
465    def test_network_watcher_monitor(self, resource_group):
466
467        SUBSCRIPTION_ID = self.settings.SUBSCRIPTION_ID
468        RESOURCE_GROUP = resource_group.name
469        NETWORK_WATCHER_NAME = self.get_resource_name("networkwatcher")
470        VIRTUAL_NETWORK_NAME = self.get_resource_name("virtualnetwork")
471        SUBNET_NAME = self.get_resource_name("subnet")
472        INTERFACE_NAME = self.get_resource_name("interface")
473        VIRTUAL_MACHINE_NAME = self.get_resource_name("virtualmachine")
474        CONNECTION_MONITOR_NAME = self.get_resource_name("connectionmonitor")
475        CONNECTION_MONITOR_NAME_V2 = self.get_resource_name("connectionmonitorv2")
476        VIRTUAL_MACHINE_EXTENSION_NAME = self.get_resource_name("virtualmachineextension")
477
478        if self.is_live:
479            self.create_vm(RESOURCE_GROUP, AZURE_LOCATION, VIRTUAL_MACHINE_NAME, VIRTUAL_NETWORK_NAME, SUBNET_NAME, INTERFACE_NAME)
480            self.create_vm_extension(RESOURCE_GROUP, AZURE_LOCATION, VIRTUAL_MACHINE_NAME, VIRTUAL_MACHINE_EXTENSION_NAME)
481
482        # Create network watcher[put]
483        BODY = {
484          "location": "eastus"
485        }
486        result = self.mgmt_client.network_watchers.create_or_update(resource_group.name, NETWORK_WATCHER_NAME, BODY)
487
488        # # Create connection monitor V2[put]
489        BODY = {
490          "location": "eastus",
491          "endpoints": [
492            {
493              "name": "vm1",
494              "resource_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Compute/virtualMachines/" + VIRTUAL_MACHINE_NAME + ""
495            },
496            # {
497            #   "name": "CanaryWorkspaceVamshi",
498            #   "resource_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.OperationalInsights/workspaces/" + WORKSPACE_NAME + "",
499            #   "filter": {
500            #     "type": "Include",
501            #     "items": [
502            #       {
503            #         "type": "AgentAddress",
504            #         "address": "npmuser"
505            #       }
506            #     ]
507            #   }
508            # },
509            {
510              "name": "bing",
511              "address": "bing.com"
512            },
513            {
514              "name": "google",
515              "address": "google.com"
516            }
517          ],
518          "test_configurations": [
519            {
520              "name": "testConfig1",
521              "test_frequency_sec": "60",
522              "protocol": "Tcp",
523              "tcp_configuration": {
524                "port": "80",
525                "disable_trace_route": False
526              }
527            }
528          ],
529          "test_groups": [
530            {
531              "name": "test1",
532              "disable": False,
533              "test_configurations": [
534                "testConfig1"
535              ],
536              "sources": [
537                "vm1",
538                # "CanaryWorkspaceVamshi"
539              ],
540              "destinations": [
541                "bing",
542                "google"
543              ]
544            }
545          ],
546          "outputs": []
547        }
548        result = self.mgmt_client.connection_monitors.begin_create_or_update(resource_group.name, NETWORK_WATCHER_NAME, CONNECTION_MONITOR_NAME_V2, BODY)
549        result = result.result()
550
551        # Create connection monitor V1[put]
552        # [Kaihui] v1 only supports api version <= 2019-06-01
553        BODY = {
554          "location": AZURE_LOCATION,
555          "source": {
556            "resource_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Compute/virtualMachines/" + VIRTUAL_MACHINE_NAME + ""
557          },
558          "destination": {
559            "address": "bing.com",
560            "port": "80"
561          },
562          "monitoring_interval_in_seconds": "60"
563        }
564        result = self.mgmt_client_v190601.connection_monitors.begin_create_or_update(resource_group.name, NETWORK_WATCHER_NAME, CONNECTION_MONITOR_NAME, BODY)
565        result = result.result()
566
567        # Get connection monitor[get]
568        result = self.mgmt_client.connection_monitors.get(resource_group.name, NETWORK_WATCHER_NAME, CONNECTION_MONITOR_NAME)
569
570        # List connection monitors[get]
571        result = self.mgmt_client.connection_monitors.list(resource_group.name, NETWORK_WATCHER_NAME)
572
573        # List connection monitors[get]
574        result = self.mgmt_client.connection_monitors.list(resource_group.name, NETWORK_WATCHER_NAME)
575
576        # Query connection monitor[post]
577        result = self.mgmt_client.connection_monitors.begin_query(resource_group.name, NETWORK_WATCHER_NAME, CONNECTION_MONITOR_NAME)
578        result = result.result()
579
580        # # Start connection monitor[post]
581        result = self.mgmt_client.connection_monitors.begin_start(resource_group.name, NETWORK_WATCHER_NAME, CONNECTION_MONITOR_NAME)
582        result = result.result()
583
584        # # Stop connection monitor[post]
585        result = self.mgmt_client.connection_monitors.begin_stop(resource_group.name, NETWORK_WATCHER_NAME, CONNECTION_MONITOR_NAME)
586        result = result.result()
587
588        # Update connection monitor tags[patch]
589        BODY = {
590          "tags": {
591            "tag1": "value1",
592            "tag2": "value2"
593          }
594        }
595        result = self.mgmt_client.connection_monitors.update_tags(resource_group.name, NETWORK_WATCHER_NAME, CONNECTION_MONITOR_NAME, BODY)
596
597        # Delete connection monitor[delete]
598        result = self.mgmt_client.connection_monitors.begin_delete(resource_group.name, NETWORK_WATCHER_NAME, CONNECTION_MONITOR_NAME)
599        result = result.result()
600
601        # Delete connection monitor[delete]
602        result = self.mgmt_client.connection_monitors.begin_delete(resource_group.name, NETWORK_WATCHER_NAME, CONNECTION_MONITOR_NAME_V2)
603        result = result.result()
604
605        # Delete network watcher[delete]
606        result = self.mgmt_client.network_watchers.begin_delete(resource_group.name, NETWORK_WATCHER_NAME)
607        result = result.result()
608
609    @RandomNameResourceGroupPreparer(location=AZURE_LOCATION)
610    def test_network_watcher_packet_capture(self, resource_group):
611
612        SUBSCRIPTION_ID = self.settings.SUBSCRIPTION_ID
613        RESOURCE_GROUP = resource_group.name
614        NETWORK_WATCHER_NAME = self.get_resource_name("networkwatcher")
615        VIRTUAL_NETWORK_NAME = self.get_resource_name("virtualnetwork")
616        SUBNET_NAME = self.get_resource_name("subnet")
617        STORAGE_ACCOUNT_NAME = self.get_resource_name("storagename")
618        NETWORK_INTERFACE_NAME = self.get_resource_name("interface")
619        VIRTUAL_MACHINE_NAME = self.get_resource_name("virtualmachine")
620        PACKET_CAPTURE_NAME = self.get_resource_name("packetcapture")
621        VIRTUAL_MACHINE_EXTENSION_NAME = self.get_resource_name("virtualmachineextension")
622
623        if self.is_live:
624            self.create_vm(RESOURCE_GROUP, AZURE_LOCATION, VIRTUAL_MACHINE_NAME, VIRTUAL_NETWORK_NAME, SUBNET_NAME, NETWORK_INTERFACE_NAME)
625            self.create_vm_extension(RESOURCE_GROUP, AZURE_LOCATION, VIRTUAL_MACHINE_NAME, VIRTUAL_MACHINE_EXTENSION_NAME)
626            self.create_storage_account(RESOURCE_GROUP, AZURE_LOCATION, STORAGE_ACCOUNT_NAME)
627
628        # Create network watcher[put]
629        BODY = {
630          "location": "eastus"
631        }
632        result = self.mgmt_client.network_watchers.create_or_update(resource_group.name, NETWORK_WATCHER_NAME, BODY)
633
634        # Create packet capture[put]
635        BODY = {
636          "target": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Compute/virtualMachines/" + VIRTUAL_MACHINE_NAME + "",
637          # "bytes_to_capture_per_packet": "10000",
638          # "total_bytes_per_session": "100000",
639          # "time_limit_in_seconds": "100",
640          "storage_location": {
641            "storage_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Storage/storageAccounts/" + STORAGE_ACCOUNT_NAME + "",
642            "storage_path": "https://" + STORAGE_ACCOUNT_NAME + ".blob.core.windows.net/capture/pc1.cap",
643            # "file_path": "D:\\capture\\pc1.cap"
644          },
645          # "filters": [
646          #   {
647          #     "protocol": "TCP",
648          #     "local_ip_address": "10.0.0.4",
649          #     "local_port": "80"
650          #   }
651          # ]
652        }
653        result = self.mgmt_client.packet_captures.begin_create(resource_group.name, NETWORK_WATCHER_NAME, PACKET_CAPTURE_NAME, BODY)
654        result = result.result()
655
656        # Get packet capture[get]
657        result = self.mgmt_client.packet_captures.get(resource_group.name, NETWORK_WATCHER_NAME, PACKET_CAPTURE_NAME)
658
659        # List packet captures[get]
660        result = self.mgmt_client.packet_captures.list(resource_group.name, NETWORK_WATCHER_NAME)
661
662        # Query packet capture status[post]
663        result = self.mgmt_client.packet_captures.begin_get_status(resource_group.name, NETWORK_WATCHER_NAME, PACKET_CAPTURE_NAME)
664        result = result.result()
665
666        # Stop packet capture[post]
667        result = self.mgmt_client.packet_captures.begin_stop(resource_group.name, NETWORK_WATCHER_NAME, PACKET_CAPTURE_NAME)
668        result = result.result()
669
670        # Delete packet capture[delete]
671        result = self.mgmt_client.packet_captures.begin_delete(resource_group.name, NETWORK_WATCHER_NAME, PACKET_CAPTURE_NAME)
672        result = result.result()
673
674    @RandomNameResourceGroupPreparer(location=AZURE_LOCATION)
675    def test_network_watcher(self, resource_group):
676
677        SUBSCRIPTION_ID = self.settings.SUBSCRIPTION_ID
678        RESOURCE_GROUP = resource_group.name
679        NETWORK_WATCHER_NAME = self.get_resource_name("networkwatcher")
680        VIRTUAL_NETWORK_NAME = self.get_resource_name("virtualnetwork")
681        VIRTUAL_NETWORK_GATEWAY_NAME = self.get_resource_name("virtualnetworkgateway")
682        PUBLIC_IP_ADDRESS_NAME = self.get_resource_name("publicipaddress")
683        SUBNET_NAME = self.get_resource_name("subnet")
684        STORAGE_ACCOUNT_NAME = self.get_resource_name("storagename")
685        NETWORK_INTERFACE_NAME = self.get_resource_name("interface")
686        IP_CONFIGURATION_NAME = self.get_resource_name("ipconfig")
687        VIRTUAL_MACHINE_NAME = self.get_resource_name("virtualmachine")
688        VIRTUAL_MACHINE_EXTENSION_NAME = self.get_resource_name("virtualmachineextension")
689
690        if self.is_live:
691            self.create_vm(RESOURCE_GROUP, AZURE_LOCATION, VIRTUAL_MACHINE_NAME, VIRTUAL_NETWORK_NAME, SUBNET_NAME, NETWORK_INTERFACE_NAME)
692            self.create_vm_extension(RESOURCE_GROUP, AZURE_LOCATION, VIRTUAL_MACHINE_NAME, VIRTUAL_MACHINE_EXTENSION_NAME)
693            self.create_storage_account(RESOURCE_GROUP, AZURE_LOCATION, STORAGE_ACCOUNT_NAME)
694
695        # Create network watcher[put]
696        BODY = {
697          "location": "eastus"
698        }
699        result = self.mgmt_client.network_watchers.create_or_update(resource_group.name, NETWORK_WATCHER_NAME, BODY)
700
701        # List network watchers[get]
702        result = self.mgmt_client.network_watchers.list(resource_group.name)
703
704        # List all network watchers[get]
705        result = self.mgmt_client.network_watchers.list_all()
706
707        # Get network watcher[get]
708        result = self.mgmt_client.network_watchers.get(resource_group.name, NETWORK_WATCHER_NAME)
709
710        # Network configuration diagnostic[post]
711        BODY = {
712          "target_resource_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Compute/virtualMachines/" + VIRTUAL_MACHINE_NAME + "",
713          "profiles": [
714            {
715              "direction": "Inbound",
716              "protocol": "TCP",
717              "source": "10.1.0.4",
718              "destination": "12.11.12.14",
719              "destination_port": "12100"
720            }
721          ]
722        }
723        result = self.mgmt_client.network_watchers.begin_get_network_configuration_diagnostic(resource_group.name, NETWORK_WATCHER_NAME, BODY)
724        result = result.result()
725
726        # TODO: raise 500
727        # Get Azure Reachability Report[post]
728        # BODY = {
729        #   "provider_location": {
730        #     "country": "United States",
731        #     "state": "washington"
732        #   },
733        #   "providers": [
734        #     "Frontier Communications of America, Inc. - ASN 5650"
735        #   ],
736        #   "azure_locations": [
737        #     "West US"
738        #   ],
739        #   "start_time": "2020-05-31T00:00:00Z",
740        #   "end_time": "2020-06-01T00:00:00Z"
741        # }
742        # result = self.mgmt_client.network_watchers.begin_get_azure_reachability_report(resource_group.name, NETWORK_WATCHER_NAME, BODY)
743        # result = result.result()
744
745        # TODO: raise 500
746        # Get Available Providers List[post]
747        # BODY = {
748        #   "azure_locations": [
749        #     "West US"
750        #   ],
751        #   "country": "United States",
752        #   "state": "washington",
753        #   "city": "seattle"
754        # }
755        # result = self.mgmt_client.network_watchers.begin_list_available_providers(resource_group.name, NETWORK_WATCHER_NAME, BODY)
756        # result = result.result()
757
758        # Get security group view[post]
759        BODY = {
760          "target_resource_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Compute/virtualMachines/" + VIRTUAL_MACHINE_NAME + ""
761        }
762        result = self.mgmt_client.network_watchers.begin_get_vm_security_rules(resource_group.name, NETWORK_WATCHER_NAME, BODY)
763        result = result.result()
764
765        # Check connectivity[post]
766        BODY = {
767          "source": {
768            "resource_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Compute/virtualMachines/" + VIRTUAL_MACHINE_NAME + ""
769          },
770          "destination": {
771            "address": "192.168.100.4",
772            "port": "3389"
773          },
774          "preferred_ipversion": "IPv4"
775        }
776        result = self.mgmt_client.network_watchers.begin_check_connectivity(resource_group.name, NETWORK_WATCHER_NAME, BODY)
777        result = result.result()
778
779        # Get Topology[post]
780        BODY = {
781          "target_resource_group_name": resource_group.name
782        }
783        result = self.mgmt_client.network_watchers.get_topology(resource_group.name, NETWORK_WATCHER_NAME, BODY)
784
785        # Get next hop[post]
786        BODY = {
787          "target_resource_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Compute/virtualMachines/" + VIRTUAL_MACHINE_NAME + "",
788          # "source_ip_address": "10.0.0.5",
789          "source_ip_address": "10.1.0.4",
790          "destination_ip_address": "10.1.0.10",
791          "target_nic_resource_id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Network/networkInterfaces/" + NETWORK_INTERFACE_NAME + ""
792        }
793        # result = self.mgmt_client.network_watchers.begin_get_next_hop(resource_group.name, NETWORK_WATCHER_NAME, BODY)
794        # result = result.result()
795
796        # Update network watcher tags[patch]
797        BODY = {
798          "tags": {
799            "tag1": "value1",
800            "tag2": "value2"
801          }
802        }
803        result = self.mgmt_client.network_watchers.update_tags(resource_group.name, NETWORK_WATCHER_NAME, BODY)
804
805        # Delete network watcher[delete]
806        result = self.mgmt_client.network_watchers.begin_delete(resource_group.name, NETWORK_WATCHER_NAME)
807        result = result.result()
808
809    @RandomNameResourceGroupPreparer(location=AZURE_LOCATION)
810    def test_network(self, resource_group):
811
812        SUBSCRIPTION_ID = self.settings.SUBSCRIPTION_ID
813        RESOURCE_GROUP = resource_group.name
814
815        VIRTUAL_NETWORK_NAME = self.get_resource_name("virtualnetwork")
816        VIRTUAL_NETWORK_NAME_2 = self.get_resource_name("virtualnetwork2")
817        SUBNET_NAME = self.get_resource_name("subnet")
818        SUBNET_NAME_2 = self.get_resource_name("subnet2")
819        STORAGE_ACCOUNT_NAME = self.get_resource_name("storagename")
820
821        NETWORK_PROFILE_NAME = self.get_resource_name("networkprofile")
822        NETWORK_SECURITY_GROUP_NAME = self.get_resource_name("networksecuritygroup")
823        NETWORK_VIRTUAL_APPLIANCE_NAME = self.get_resource_name("networkvirtualapp")
824        SECURITY_RULE_NAME = self.get_resource_name("securityrule")
825        VIRTUAL_WAN_NAME = self.get_resource_name("virtualwan")
826        VIRTUAL_HUB_NAME = self.get_resource_name("virtualhub")
827
828        if self.is_live:
829            self.create_virtual_hub(AZURE_LOCATION, RESOURCE_GROUP, VIRTUAL_WAN_NAME, VIRTUAL_HUB_NAME)
830            self.create_storage_account(RESOURCE_GROUP, AZURE_LOCATION, STORAGE_ACCOUNT_NAME)
831            self.create_virtual_network(RESOURCE_GROUP, AZURE_LOCATION, VIRTUAL_NETWORK_NAME, SUBNET_NAME)
832            self.create_virtual_network(RESOURCE_GROUP, AZURE_LOCATION, VIRTUAL_NETWORK_NAME_2, SUBNET_NAME_2)
833
834        # Create network profile defaults[put]
835        BODY = {
836          "location": "eastus",
837          "container_network_interface_configurations": [
838            {
839              "name": "eth1",
840              "ip_configurations": [
841                {
842                  "name": "ipconfig1",
843                  "subnet": {
844                    "id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Network/virtualNetworks/" + VIRTUAL_NETWORK_NAME_2 + "/subnets/" + SUBNET_NAME_2 + ""
845                  }
846                }
847              ]
848            }
849          ]
850        }
851        result = self.mgmt_client.network_profiles.create_or_update(resource_group.name, NETWORK_PROFILE_NAME, BODY)
852
853        # Create network security group[put]
854        BODY = {
855          "location": "eastus"
856        }
857        result = self.mgmt_client.network_security_groups.begin_create_or_update(resource_group.name, NETWORK_SECURITY_GROUP_NAME, BODY)
858        result = result.result()
859
860        # # Create network security group with rule[put]
861        # BODY = {
862        #   "properties": {
863        #     "security_rules": [
864        #       {
865        #         "name": "rule1",
866        #         "properties": {
867        #           "protocol": "*",
868        #           "source_address_prefix": "*",
869        #           "destination_address_prefix": "*",
870        #           "access": "Allow",
871        #           "destination_port_range": "80",
872        #           "source_port_range": "*",
873        #           "priority": "130",
874        #           "direction": "Inbound"
875        #         }
876        #       }
877        #     ]
878        #   },
879        #   "location": "eastus"
880        # }
881        # result = self.mgmt_client.network_security_groups.begin_create_or_update(resource_group.name, NETWORK_SECURITY_GROUP_NAME, BODY)
882        # result = result.result()
883
884        # TODO: (InvalidResourceType) The resource type could not be found in the namespace 'Microsoft.Network' for api version '2020-03-01'
885        # Create NetworkVirtualAppliance[put]
886        # BODY = {
887        #   "tags": {
888        #     "key1": "value1"
889        #   },
890        #   "sku": {
891        #     "vendor": "Cisco SDWAN",
892        #     "bundled_scale_unit": "1",
893        #     "market_place_version": "12.1"
894        #   },
895        #   "identity": {
896        #     "type": "UserAssigned",
897        #     "user_assigned_identities": {}
898        #   },
899        #   "location": "West US",
900        #   "virtual_hub": {
901        #     "id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Network/virtualHubs/" + VIRTUAL_HUB_NAME + ""
902        #   },
903        #   "boot_strap_configuration_blob": [
904        #     "https://" + STORAGE_ACCOUNT_NAME + ".blob.core.windows.net/csrncvhdstoragecont/csrbootstrapconfig"
905        #   ],
906        #   "cloud_init_configuration_blob": [
907        #     "https://" + STORAGE_ACCOUNT_NAME + ".blob.core.windows.net/csrncvhdstoragecont/csrcloudinitconfig"
908        #   ],
909        #   "virtual_appliance_asn": "10000"
910        # }
911        # result = self.mgmt_client.network_virtual_appliances.begin_create_or_update(resource_group.name, NETWORK_VIRTUAL_APPLIANCE_NAME, BODY)
912        # result = result.result()
913
914        # Create security rule[put]
915        BODY = {
916          "protocol": "*",
917          "source_address_prefix": "10.0.0.0/8",
918          "destination_address_prefix": "11.0.0.0/8",
919          "access": "Deny",
920          "destination_port_range": "8080",
921          "source_port_range": "*",
922          "priority": "100",
923          "direction": "Outbound"
924        }
925        result = self.mgmt_client.security_rules.begin_create_or_update(resource_group.name, NETWORK_SECURITY_GROUP_NAME, SECURITY_RULE_NAME, BODY)
926        result = result.result()
927
928        # DefaultSecurityRuleList[get]
929        result = self.mgmt_client.default_security_rules.list(resource_group.name, NETWORK_SECURITY_GROUP_NAME)
930
931        DEFAULT_SECURITY_RULE_NAME = "AllowVnetInBound"
932        # DefaultSecurityRuleGet[get]
933        result = self.mgmt_client.default_security_rules.get(resource_group.name, NETWORK_SECURITY_GROUP_NAME, DEFAULT_SECURITY_RULE_NAME)
934
935        # Get network security rule in network security group[get]
936        result = self.mgmt_client.security_rules.get(resource_group.name, NETWORK_SECURITY_GROUP_NAME, SECURITY_RULE_NAME)
937
938        # List network security rules in network security group[get]
939        result = self.mgmt_client.security_rules.list(resource_group.name, NETWORK_SECURITY_GROUP_NAME)
940
941        # Get NetworkVirtualAppliance[get]
942        # result = self.mgmt_client.network_virtual_appliances.get(resource_group.name, NETWORK_VIRTUAL_APPLIANCE_NAME)
943
944        # Get network security group[get]
945        result = self.mgmt_client.network_security_groups.get(resource_group.name, NETWORK_SECURITY_GROUP_NAME)
946
947        # Get network profile[get]
948        result = self.mgmt_client.network_profiles.get(resource_group.name, NETWORK_PROFILE_NAME)
949
950        # Get network profile with container network interfaces[get]
951        result = self.mgmt_client.network_profiles.get(resource_group.name, NETWORK_PROFILE_NAME)
952
953        # List all Network Virtual Appliance for a given resource group[get]
954        # result = self.mgmt_client.network_virtual_appliances.list_by_resource_group(resource_group.name)
955
956        # List network security groups in resource group[get]
957        result = self.mgmt_client.network_security_groups.list(resource_group.name)
958
959        # List resource group network profiles[get]
960        result = self.mgmt_client.network_profiles.list(resource_group.name)
961
962        # List all Network Virtual Appliances for a given subscription[get]
963        # result = self.mgmt_client.network_virtual_appliances.list()
964
965        # List all network security groups[get]
966        result = self.mgmt_client.network_security_groups.list_all()
967
968        # List all network profiles[get]
969        result = self.mgmt_client.network_profiles.list_all()
970
971        # # Update NetworkVirtualAppliance[patch]
972        # BODY = {
973        #   "tags": {
974        #     "key1": "value1",
975        #     "key2": "value2"
976        #   }
977        # }
978        # result = self.mgmt_client.network_virtual_appliances.update_tags(resource_group.name, NETWORK_VIRTUAL_APPLIANCE_NAME, BODY)
979
980        # Update network security group tags[patch]
981        BODY = {
982          "tags": {
983            "tag1": "value1",
984            "tag2": "value2"
985          }
986        }
987        result = self.mgmt_client.network_security_groups.update_tags(resource_group.name, NETWORK_SECURITY_GROUP_NAME, BODY)
988
989        # Update network profile tags[patch]
990        BODY = {
991          "tags": {
992            "tag1": "value1",
993            "tag2": "value2"
994          }
995        }
996        result = self.mgmt_client.network_profiles.update_tags(resource_group.name, NETWORK_PROFILE_NAME, BODY)
997
998        # Delete network security rule from network security group[delete]
999        result = self.mgmt_client.security_rules.begin_delete(resource_group.name, NETWORK_SECURITY_GROUP_NAME, SECURITY_RULE_NAME)
1000        result = result.result()
1001
1002        # # Delete NetworkVirtualAppliance[delete]
1003        # result = self.mgmt_client.network_virtual_appliances.begin_delete(resource_group.name, NETWORK_VIRTUAL_APPLIANCE_NAME)
1004        # result = result.result()
1005
1006        # Delete network security group[delete]
1007        result = self.mgmt_client.network_security_groups.begin_delete(resource_group.name, NETWORK_SECURITY_GROUP_NAME)
1008        result = result.result()
1009
1010        # Delete network profile[delete]
1011        result = self.mgmt_client.network_profiles.begin_delete(resource_group.name, NETWORK_PROFILE_NAME)
1012        result = result.result()
1013
1014
1015#------------------------------------------------------------------------------
1016if __name__ == '__main__':
1017    unittest.main()
1018