Esempio n. 1
0
        public static bool AddNetwork(
            dynamic json, string networkUuid, string networkName)
        {
            if (NtnxUtil.PassThroughNonNull(networkUuid))
            {
                json.spec.resources.nic_list[0].subnet_reference.uuid = networkUuid;
            }
            else if (NtnxUtil.PassThroughNonNull(networkName))
            {
                // TODO: grab images by name.
                var networks = GetSubnetCmdlet.GetSubnetsByName(networkName);
                if (networks.Length > 1)
                {
                    for (int i = 0; i < networks.Length; ++i)
                    {
                        Console.WriteLine("Network " + i.ToString(CultureInfo.InvariantCulture) + ": " + networks[i].Uuid);
                    }

                    return(false);
                }
                else
                {
                    json.spec.resources.nic_list[0].subnet_reference.uuid =
                        networks[0].Uuid;
                }
            }

            return(true);
        }
Esempio n. 2
0
        // TODO: figure out Nutanix's analog for NumCpu.
        //       NumVcpusPerSocket is not correct.
        protected override void ProcessRecord()
        {
            // TODO: maybe should not rely on 'json' to generate request?
            if (Name != null)
            {
                VM.Json.spec.name = Name;
            }

            if (Description != null)
            {
                VM.Json.spec.description = Description;
            }

            if (MemoryMB != null)
            {
                VM.Json.spec.resources.memory_size_mib = MemoryMB;
            }

            VM.Json.api_version = "3.1";
            VM.Json.Property("status").Remove();

            // TODO: return Task object from the RestCall.
            WriteObject(Task.FromUuidInJson(
                            NtnxUtil.RestCall("vms/" + VM.Uuid, "PUT", VM.Json.ToString())));
        }
Esempio n. 3
0
        public static bool AddImage(
            dynamic json, string imageUuid, string imageName)
        {
            if (NtnxUtil.PassThroughNonNull(imageUuid))
            {
                json.spec.resources.disk_list[0].data_source_reference.uuid = imageUuid;
            }
            else if (NtnxUtil.PassThroughNonNull(imageName))
            {
                // TODO: grab images by name.
                var images = GetImageCmdlet.GetImagesByName(imageName);
                if (images.Length > 1)
                {
                    // Ambiguous: found more than 1 image with the same name
                    for (int i = 0; i < images.Length; ++i)
                    {
                        Console.WriteLine("Image " + i.ToString(CultureInfo.InvariantCulture) + ": " + images[i].Uuid);
                    }

                    return(false);
                }
                else
                {
                    json.spec.resources.disk_list[0].data_source_reference.uuid =
                        images[0].Uuid;
                }
            }

            return(true);
        }
Esempio n. 4
0
        public static Task GetTaskByUuid(string uuid)
        {
            // TODO: validate using UUID regexes that 'uuid' is in correct format.
            var json = NtnxUtil.RestCall("tasks/" + uuid, "GET", string.Empty /* requestBody */);

            return(new Task(json));
        }
Esempio n. 5
0
        // Save authentication info.
        public static void Connect(
            string server,
            string username,
            System.Security.SecureString password,
            bool acceptinvalidsslcerts)
        {
            HttpClientHandler handler = null;

            // Create handle to ignore invalid SSL certificates.
            if (acceptinvalidsslcerts)
            {
                handler = new HttpClientHandler();
                handler.ClientCertificateOptions = ClientCertificateOption.Manual;
                handler.ServerCertificateCustomValidationCallback =
                    (httpRequestMessage, cert, cetChain, policyErrors) =>
                {
                    return(true);
                };
            }

            NtnxUtil.Server  = server;
            NtnxUtil.PSCreds = new System.Management.Automation.PSCredential(
                username, password);

            // Create HttpClient.
            var    client     = new HttpClient(handler);
            string authHeader = NtnxUtil.GetAuthHeader();

            client.BaseAddress = new Uri("https://" + server + ":9440");
            client.DefaultRequestHeaders.Add("Authorization", "Basic " + authHeader);
            client.DefaultRequestHeaders.Add("Accept", "application/json");
            client.DefaultRequestHeaders.Add(
                "X-Nutanix-Client-Type", "Nutanix.PowerShell.SDK");
            NtnxUtil.Client = client;
        }
Esempio n. 6
0
        protected override void ProcessRecord()
        {
            var     url    = "subnets";
            var     method = "POST";
            var     str    = @"{
      ""api_version"": ""3.1"",
      ""metadata"": {
        ""kind"": ""subnet"",
        ""name"": """ + Name + @"""
      },
      ""spec"": {
        ""description"": """ + Description + @""",
        ""name"": """ + Name + @""",
        ""resources"": {
          ""subnet_type"": ""VLAN"",
          ""vlan_id"": " + VlanId + @",
        }
      }
    }";
            dynamic json   = JsonConvert.DeserializeObject(str);

            if (Cluster != null)
            {
                json.spec.cluster_reference      = new Newtonsoft.Json.Linq.JObject();
                json.spec.cluster_reference.kind = "cluster";
                json.spec.cluster_reference.uuid = Cluster.Uuid;
                json.spec.cluster_reference.name = Cluster.Name;
            }

            // TODO: should use Task.
            WriteObject(
                Task.FromUuidInJson(NtnxUtil.RestCall(url, method, json.ToString())));
        }
Esempio n. 7
0
        private static Image GetImageByUuid(string uuid)
        {
            // TODO: validate using UUID regexes that 'uuid' is in correct format.
            var json = NtnxUtil.RestCall("images/" + uuid, "GET", string.Empty /* requestBody */);

            return(new Image(json));
        }
Esempio n. 8
0
        public static Subnet GetSubnetByUuid(string uuid)
        {
            // TODO: validate using UUID regexes that 'uuid' is in correct format.
            var json = NtnxUtil.RestCall("subnets/" + uuid, "GET", string.Empty /* requestBody */);

            return(new Subnet(json));
        }
Esempio n. 9
0
        protected override void ProcessRecord()
        {
            var url    = "images";
            var method = "POST";
            var str    = @"{
      ""api_version"": ""3.1"",
      ""metadata"": {
        ""kind"": ""image"",
        ""name"": """ + this.Name + @"""
      },
      ""spec"": {
        ""description"": """ + this.Description + @""",
        ""name"": """ + this.Name + @""",
        ""resources"": {
          ""image_type"": ""DISK_IMAGE"",
          ""source_uri"": """ + this.URL + @"""
        }
      }
    }";

            var task = Task.FromUuidInJson(NtnxUtil.RestCall(url, method, str));

            if (this.runAsync)
            {
                WriteObject(task);
            }
            else
            {
                WriteObject(task.Wait());
            }
        }
Esempio n. 10
0
 protected override void ProcessRecord()
 {
     if (NtnxUtil.PassThroughNonNull(Uuid))
     {
         // TODO: WriteObject Task
         DeleteImageByUuid(Uuid);
     }
 }
Esempio n. 11
0
        // If no params specified, then get VM with 'name'.
        public static Task DeleteVmByName(string name)
        {
            var vm = GetVmCmdlet.GetVmByName(name);

            if (vm != null)
            {
                return(Task.FromUuidInJson(NtnxUtil.RestCall("vms/" + vm.Uuid, "DELETE", string.Empty)));
            }

            return(null);
        }
Esempio n. 12
0
        protected override void ProcessRecord()
        {
            if (NtnxUtil.PassThroughNonNull(Uuid))
            {
                WriteObject(GetSubnetByUuid(Uuid));
                return;
            }

            var subnets = GetAllSubnets(BuildRequestBody());

            WriteObject(subnets);
        }
Esempio n. 13
0
        protected override void ProcessRecord()
        {
            if (NtnxUtil.PassThroughNonNull(Uuid))
            {
                WriteObject(GetImageByUuid(Uuid));
                return;
            }

            var images = GetAllImages(BuildRequestBody());

            WriteObject(images);
        }
Esempio n. 14
0
        // Grab all VMs.
        public static Vm[] GetAllVms()
        {
            int pageSize    = 20;
            int total_count = 0;

            string request = @"{
            ""kind"": ""vm"",
            ""offset"": 0,
            ""length"": 1
      }";

            var json = NtnxUtil.RestCall("vms/list", "POST", request);

            if (json == null || json.entities == null || json.metadata == null)
            {
                throw new NtnxException("REST API call likely failed or server response does not contain needed information");
            }

            total_count = json.metadata.total_matches;

            if (total_count == 0)
            {
                return(Array.Empty <Vm>());
            }

            Vm[] vms = new Vm[total_count];
            Parallel.ForEach(
                Partitioner.Create(0, total_count, pageSize),
                new ParallelOptions {
                MaxDegreeOfParallelism = 4
            },
                range =>
            {
                request = @"{
              ""kind"": ""vm"",
              ""offset"": " + range.Item1.ToString() + @",
              ""length"": 20
            }";

                var jsonParallel = NtnxUtil.RestCall("vms/list", "POST", request);

                for (int i = 0; i < jsonParallel.entities.Count; i++)
                {
                    lock (vms)
                    {
                        vms[range.Item1 + i] = new Vm(jsonParallel.entities[i]);
                    }
                }
            });

            return(vms);
        }
Esempio n. 15
0
        // If no params specified, then get VM with 'name'.
        public static Vm GetVmByName(string name)
        {
            var reqBody = "{\"filter\": \"vm_name==" + name + "\"}";
            var json    = NtnxUtil.RestCall("vms/list", "POST", reqBody);

            if (json.entities.Count == 0)
            {
                var message = string.Format(CultureInfo.InvariantCulture, "VM not found by the name of {0}", name);
                throw new NtnxException(message);
            }

            return(new Vm(json.entities[0]));
        }
Esempio n. 16
0
        protected override void ProcessRecord()
        {
            if (Name != null)
            {
                Subnet.Json.spec.name = Name;
            }

            if (VlanId != null)
            {
                Subnet.Json.spec.resources.vlan_id = VlanId;
            }

            Subnet.Json.api_version = "3.1";
            NtnxUtil.RestCall("subnets/" + Subnet.Uuid, "PUT", Subnet.Json.ToString());
        }
Esempio n. 17
0
        // Given the parameters, build request body for '/images/list'.
        public dynamic BuildRequestBody()
        {
            dynamic json = JsonConvert.DeserializeObject("{}");

            if (Max != null)
            {
                json.length = Max;
            }

            if (NtnxUtil.PassThroughNonNull(Name))
            {
                json.filter = "name==" + Name;
            }

            return(json);
        }
Esempio n. 18
0
        protected override void ProcessRecord()
        {
            VM.Json.spec.resources.power_state = "ON";
            VM.Json.api_version = "3.1"; // TODO: remove api_version field set.
            var task = Task.FromUuidInJson(
                NtnxUtil.RestCall("vms/" + VM.Uuid, "PUT", VM.Json.ToString()));

            if (runAsync)
            {
                WriteObject(task);
            }
            else
            {
                WriteObject(task.Wait());
            }
        }
Esempio n. 19
0
        // Grab all VMs.
        // REST: /clusters/list
        public static Cluster[] GetAllClusters()
        {
            var json = NtnxUtil.RestCall("clusters/list", "POST", "{}");

            if (json.entities.Count == 0)
            {
                return(Array.Empty <Cluster>());
            }

            Cluster[] clusters = new Cluster[json.entities.Count];
            for (int i = 0; i < json.entities.Count; ++i)
            {
                clusters[i] = new Cluster(json.entities[i]);
            }

            return(clusters);
        }
Esempio n. 20
0
        protected override void ProcessRecord()
        {
            if (NtnxUtil.PassThroughNonNull(Uuid))
            {
                WriteObject(GetTaskByUuid(Uuid));
                return;
            }

            if (Task != null)
            {
                WriteObject(GetTaskByUuid(Task.Uuid));
                return;
            }

            var message = string.Format(CultureInfo.InvariantCulture, "Expected either -Uuid or -Task. We were given Uuid {0} and/or Task {1}", Uuid, Task);

            throw new NtnxException(message);
        }
Esempio n. 21
0
        protected override void ProcessRecord()
        {
            if (Name != null)
            {
                Image.Json.spec.name = Name;
            }

            Image.Json.api_version = "3.1";
            var task = Task.FromUuidInJson(
                NtnxUtil.RestCall("images/" + Image.Uuid, "PUT", Image.Json.ToString()));

            if (runAsync)
            {
                WriteObject(task);
            }
            else
            {
                WriteObject(task.Wait());
            }
        }
Esempio n. 22
0
        protected override void ProcessRecord()
        {
            if (string.IsNullOrEmpty(Name) && string.IsNullOrEmpty(Uuid))
            {
                // If no params specified, then get all VMs.
                WriteObject(GetAllVms());
                return;
            }

            if (NtnxUtil.PassThroughNonNull(Uuid))
            {
                WriteObject(GetVmByUuid(Uuid));
                return;
            }

            if (NtnxUtil.PassThroughNonNull(Name))
            {
                WriteObject(GetVmByName(Name));
            }
        }
Esempio n. 23
0
        protected override void ProcessRecord()
        {
            if (this.VM != null)
            {
                this.Uuid = this.VM.Uuid;
            }

            if (string.IsNullOrEmpty(this.Name) && string.IsNullOrEmpty(this.Uuid))
            {
                var message = string.Format(CultureInfo.InvariantCulture, "Need -Name or -Uuid. We were given Name {0} and/or UUID {1}", this.Name, this.Uuid);
                throw new NtnxException(message);
            }

            if (NtnxUtil.PassThroughNonNull(Uuid))
            {
                WriteObject(DeleteVmByUuid(Uuid));
                return;
            }

            if (NtnxUtil.PassThroughNonNull(Name))
            {
                WriteObject(DeleteVmByName(Name));
            }
        }
Esempio n. 24
0
 public static void DeleteImageByUuid(string uuid)
 {
     // TODO: validate using UUID regexes that 'uuid' is in correct format.
     NtnxUtil.RestCall("images/" + uuid, "DELETE", string.Empty /* requestBody */);
 }
Esempio n. 25
0
 public static Subnet[] GetAllSubnets(string reqBody)
 {
     return(NtnxUtil.FromJson <Subnet>(
                NtnxUtil.RestCall("subnets/list", "POST", reqBody),
                (Func <dynamic, Subnet>)(j => new Subnet(j))));
 }
Esempio n. 26
0
 public static Image[] GetAllImages(string reqBody)
 {
     return(NtnxUtil.FromJson <Image>(NtnxUtil.RestCall("images/list", "POST", reqBody), (Func <dynamic, Image>)(j => new Image(j))));
 }
Esempio n. 27
0
        protected override void ProcessRecord()
        {
            var     url    = "vms";
            var     method = "POST";
            var     str    = @"{
      ""api_version"": ""3.1"",
      ""metadata"": {
        ""kind"": ""vm""
      },
      ""spec"": {
        ""resources"": {
          ""memory_size_mib"": " + this.MemorySizeMib.ToString(CultureInfo.InvariantCulture) + @",
          ""num_vcpus_per_socket"": " + this.NumVcpusPerSocket.ToString(CultureInfo.InvariantCulture) + @",
          ""num_sockets"": " + this.NumSockets.ToString(CultureInfo.InvariantCulture) + @",
          ""power_state"": """ + this.PowerState + @""",
          ""disk_list"": [
            {
              ""data_source_reference"": {
                ""kind"": ""image""
              },
              ""device_properties"": {
                ""device_type"": ""DISK""
              }
            }
          ],
          ""nic_list"": [
            {
              ""subnet_reference"": {
                ""kind"": ""subnet""
              }
            }
          ]
        },
        ""name"": """ + Name + @"""
      }
    }";
            dynamic json   = JsonConvert.DeserializeObject(str);

            if (!AddImage(json, this.ImageUuid, this.ImageName))
            {
                return;
            }

            if (!AddNetwork(json, NetworkUuid, NetworkName))
            {
                return;
            }

            if (!AddCluster(json, Cluster))
            {
                return;
            }

            // TODO: make cluster_reference required if talking to PC. But not needed
            // if talking to PE.
            var task = Task.FromUuidInJson(NtnxUtil.RestCall(url, method, json.ToString()));

            if (runAsync)
            {
                WriteObject(task);
            }
            else
            {
                WriteObject(task.Wait());
            }
        }
Esempio n. 28
0
 // Delete Vm using 'uuid'.
 public static Task DeleteVmByUuid(string uuid)
 {
     // TODO: validate using UUID regexes that 'uuid' is in correct format.
     return(Task.FromUuidInJson(NtnxUtil.RestCall("vms/" + uuid, "DELETE", string.Empty)));
 }