file_path
stringlengths
21
224
content
stringlengths
0
80.8M
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/ovami/defaults/main.yml
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion # "none" or "system" dcv_authentication_method: system
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/ovami/meta/main.yml
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion --- galaxy_info: role_name: ovami author: NVIDIA Corporation description: Omniverse AMI standalone: false dependencies: - { role: system } - { role: docker } - { role: nvidia } - { role: rdesktop }
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/docker/tasks/main.yml
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion --- - name: Add Docker apt key apt_key: url="https://download.docker.com/linux/ubuntu/gpg" state=present - name: Add Docker apt package repository apt_repository: repo="deb https://download.docker.com/linux/ubuntu {{ ansible_distribution_release }} stable" state=present mode=644 - name: Install docker packages apt: name={{ item }} state=latest update_cache=yes with_items: - docker-ce - docker-ce-cli - docker-compose - name: Create docker group group: name=docker state=present - name: Add user ubuntu to docker group user: name=ubuntu groups=docker append=yes state=present - name: Reset connection so docker group is picked up meta: reset_connection
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/system/handlers/main.yml
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion # reboot - name: Reboot and wait reboot: post_reboot_delay=5 connect_timeout=3 reboot_timeout=600 listen: reboot
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/system/tasks/id.yml
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion --- # change color of the bash prompt - name: Enable color of the bash prompt lineinfile: path: /home/{{ ansible_user }}/.bashrc line: "force_color_prompt=yes" insertbefore: if \[ \-n \"\$force_color_prompt\" backup: yes - name: Change color of the bash prompt lineinfile: path: /home/{{ ansible_user }}/.bashrc regexp: "^ PS1='\\${debian_chroot:\\+\\(\\$debian_chroot\\)}\\\\\\[\\\\033\\[01;32m\\\\\\]\\\\u@\\\\h\\\\\\[\\\\033\\[00m\\\\\\]:\\\\\\[\\\\033\\[01;34m\\\\\\]\\\\w\\\\\\[\\\\033\\[00m\\\\\\]\\\\\\$ '" line: " PS1='${debian_chroot:+($debian_chroot)}\\[\\033[01;{{ prompt_ansi_color }}m\\]\\u\\[\\033[01;{{ prompt_ansi_color }}m\\]@\\h\\[\\033[00m\\]:\\[\\033[01;34m\\]\\w\\[\\033[00m\\]\\$ '" backup: yes # set hostname - set_fact: hostname: "{{ (application_name + '-' + deployment_name) | replace('_', '-') }}" - debug: msg: "hostname: {{ hostname }}" - name: Set hostname [1] hostname: name: "{{ hostname }}" - name: Set hostname [2] lineinfile: path: /etc/hosts line: "127.0.0.1 {{ hostname }}"
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/system/tasks/swap.yml
- name: Disable swap and remove /swapfile shell: "[[ -f /swapfile ]] && (swapoff -a && rm -f /swapfile) || echo 'no swap file found'" - name: Create /swapfile shell: "fallocate -l {{ swap_size }} /swapfile" - name: Set permissions on /swapfile shell: "chmod 600 /swapfile" - name: Make swap in /swapfile shell: "mkswap /swapfile" - name: Add /swapfile to fstab lineinfile: path: /etc/fstab line: "/swapfile none swap sw 0 0" - name: Enable swap shell: "swapon -a"
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/system/tasks/password.yml
# set ubuntu user password to "ubuntu" # this is supposed to change with userdata - name: Create password hash shell: python3 -c "import crypt; print(crypt.crypt('{{ system_user_password }}'))" register: system_user_password_hash - name: Set password for "{{ ansible_user }}" user user: name: "{{ ansible_user }}" password: "{{ system_user_password_hash.stdout }}"
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/system/tasks/main.yml
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion --- - name: Check OS name and version assert: that="ansible_distribution == 'Ubuntu'" # add extra ssh ports - name: Change SSH port to {{ ssh_port }} include: custom_ssh.yml when: ssh_port != 22 - name: Upgrade the OS (apt-get dist-upgrade) apt: upgrade=dist update_cache=yes - name: Set OS user password include: password.yml - name: Disable IPv6 for apt-get copy: dest: /etc/apt/apt.conf.d/99force-ipv4 src: etc.apt.apt.conf.d.99force-ipv4 mode: 0644 - name: Disable unattended upgrades copy: src: etc.apt.apt.conf.d.20auto-upgrades dest: /etc/apt/apt.conf.d/20auto-upgrades mode: 0644 # add packages for convinience - name: Install common apt packages apt: name=htop state=latest - name: Add user ubuntu to sudo group user: name=ubuntu groups=sudo append=yes state=present - name: Check if reboot required stat: path: /var/run/reboot-required register: reboot_required_file - name: Reboot and wait reboot: post_reboot_delay: 5 connect_timeout: 3 reboot_timeout: 600 when: reboot_required_file.stat.exists == true # - set hostname # - set prompt color and hostname - include: id.yml # swap - name: Check if swap is enabled shell: "swapon -s | wc -l" register: swap_enabled tags: - skip_in_image - import_tasks: swap.yml when: swap_enabled.stdout | int == 0 tags: - skip_in_image
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/system/tasks/custom_ssh.yml
# change ssh port to custom value - name: Set SSH port to {{ ssh_port }} lineinfile: path: /etc/ssh/sshd_config line: "Port {{ item }}" state: present mode: 0644 with_items: - "22" - "{{ ssh_port }}" - name: Create ufw profile for the custom ssh port template: src=custom_ssh.ufwprofile dest=/etc/ufw/applications.d/custom_ssh mode=644 - name: Allow incoming connections to the custom ssh port ufw: rule=allow name=custom_ssh - name: Restart sshd service: name=sshd state=restarted - name: Make Ansible to use new ssh port set_fact: ansible_port: "{{ ssh_port }}"
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/system/defaults/main.yml
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion # ssh port (in addition to 22) ssh_port: 22 # format that is accepted by fallocate swap_size: 32G # password for the system user system_user_password:
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/handlers/main.yml
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion - name: Restart NX server service: > name=nxserver state=restarted listen: nx_restart
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/tasks/novnc.yml
# Install noVNC - name: Prerequisites apt: name: snapd state: latest # Install noVNC via snap package - name: Install noVNC snap: name: novnc state: present - name: Add noVNC systemd config template: src=novnc.service dest=/etc/systemd/system mode=0444 owner=root group=root - name: Start noVNC systemd: name=novnc daemon_reload=yes enabled=yes state=restarted
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/tasks/busid.yml
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion # update BusID in xorg.conf before GDM start # executed from /etc/gdm3/PreSession/Default - name: Create BusID updater copy: content: | #!/bin/bash BUS_ID=$(nvidia-xconfig --query-gpu-info | grep 'PCI BusID' | head -n 1 | cut -c15-) sed -i "s/BusID.*$/BusID \"$BUS_ID\"/" /etc/X11/xorg.conf dest: /opt/update-busid mode: 0755 # add /opt/update-busid to /etc/gdm3/PreSession/Default - name: Add BusID updater to /etc/gdm3/PreSession/Default lineinfile: path: /etc/gdm3/PreSession/Default line: /opt/update-busid insertafter: EOF state: present
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/tasks/vnc.yml
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion --- - name: Prerequisites (PIP packages) pip: name: "{{ item }}" state: latest with_items: - pexpect - name: Install x11vnc and helper util apt: name={{ item }} update_cache=yes state=latest with_items: - x11vnc - expect - name: Add x11vnc systemd config template: src=x11vnc-ubuntu.service dest=/etc/systemd/system mode=0444 owner=root group=root - name: Start x11vnc systemd: name=x11vnc-ubuntu daemon_reload=yes enabled=yes state=restarted - name: Clear VNC password file: path: /home/ubuntu/.vnc/passwd state: absent - name: Set VNC password expect: command: /usr/bin/x11vnc -storepasswd responses: (?i).*password:.*: "{{ vnc_password }}\r" (?i)write.*: "y\r" creates: /home/ubuntu/.vnc/passwd become_user: ubuntu tags: - skip_in_image - name: Cleanup VNC password file: path: /home/ubuntu/.vnc/passwd state: absent tags: - never - cleanup
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/tasks/utils.yml
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion # install extra packages - name: Install extra packages apt: name={{ item }} state=latest update_cache=yes install_recommends=no with_items: - eog # EOG image viewer (https://help.gnome.org/users/eog/stable/)
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/tasks/vscode.yml
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion - name: Prerequisites apt: name: snapd state: latest # install visual studio code - name: Install Visual Studio Code snap: name: code state: present classic: yes # install remote development extension pack - name: Install Remote Development extension pack shell: code --install-extension ms-vscode-remote.vscode-remote-extensionpack become_user: "{{ ansible_user }}" # make sure desktop directory exists - name: Make sure desktop directory exists file: path: /home/{{ ansible_user }}/Desktop state: directory mode: 0755 owner: "{{ ansible_user }}" group: "{{ ansible_user }}" # create a desktop shortcut for visual studio code - name: Create desktop shortcut for Visual Studio Code copy: dest: /home/{{ ansible_user }}/Desktop/vscode.desktop mode: 0755 owner: "{{ ansible_user }}" group: "{{ ansible_user }}" content: | [Desktop Entry] Version=1.0 Type=Application Name=Visual Studio Code GenericName=Text Editor Comment=Edit text files Exec=/snap/bin/code --no-sandbox --unity-launch %F Icon=/snap/code/current/meta/gui/vscode.png StartupWMClass=Code StartupNotify=true Terminal=false Categories=Utility;TextEditor;Development;IDE; MimeType=text/plain;inode/directory; Actions=new-empty-window; Keywords=vscode; become_user: "{{ ansible_user }}" - name: Allow execution of desktop icon for Orbit shell: gio set "/home/{{ ansible_user }}/Desktop/{{ item }}" metadata::trusted true become_user: "{{ ansible_user }}" with_items: - vscode.desktop
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/tasks/nomachine.yml
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion --- # @see https://downloads.nomachine.com/download/?id=2 for new versions - name: Download NoMachine server get_url: url: https://download.nomachine.com/download/8.9/Linux/nomachine_8.9.1_1_amd64.deb dest: /tmp/nomachine.deb mode: 0644 timeout: 600 # 10 minutes - name: Install NoMachine server apt: deb: /tmp/nomachine.deb state: present - name: Create NX config dir file: > path=/home/ubuntu/.nx/config state=directory owner=ubuntu group=ubuntu - name: Link authorized keys to NX config file: > src=/home/ubuntu/.ssh/authorized_keys dest=/home/ubuntu/.nx/config/authorized.crt state=link owner=ubuntu group=ubuntu notify: nx_restart # add env var DISPLAY to /usr/lib/systemd/system/nxserver.service - name: Add DISPLAY env var to nxserver.service lineinfile: path: /usr/lib/systemd/system/nxserver.service line: Environment="DISPLAY=:0" insertafter: "\\[Service\\]" state: present # restart nxserver.service on GDM init (fix for "no display detected" error) - name: Restart nxserver.service on GDM init lineinfile: path: /etc/gdm3/PreSession/Default line: (/usr/bin/sleep 5 && /usr/bin/systemctl restart nxserver.service) & insertafter: EOF state: present - name: Do daemon-reload systemd: daemon_reload: yes
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/tasks/virtual-display.yml
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion --- - name: Copy EDID file template: src=vdisplay.edid dest=/etc/X11/vdisplay.edid mode=644 notify: reboot - name: Get PCI Bus ID of the first GPU shell: nvidia-xconfig --query-gpu-info | grep 'PCI BusID' | head -n 1 | cut -c15- register: GPU0_PCI_BUS_ID - name: Write X11 config template: src=xorg.conf dest=/etc/X11/xorg.conf mode=644 notify: reboot - name: Create Xauthority file file: path: /home/{{ ansible_user }}/.Xauthority state: touch owner: "{{ ansible_user }}" group: "{{ ansible_user }}" mode: 0666
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/tasks/main.yml
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion --- # check if we need to skip stuff - name: Check installed services service_facts: - name: Prerequisites (1) apt: | name="{{ item }}" state=latest update_cache=yes install_recommends=no with_items: - ubuntu-desktop - python3-pip # install only if ubuntu 20 - name: Prerequisites (2) apt: name=yaru-theme-gtk state=latest when: ansible_distribution_release == "focal" - name: Configure desktop environment import_tasks: desktop.yml - name: Virtual display import_tasks: virtual-display.yml # updates bus id of the gpu in the xorg.conf file # needed for starting from the image without ansible - name: Bus ID updater import_tasks: busid.yml # install misc utils - name: Misc utils import_tasks: utils.yml # install visual studio code - name: Visual Studio Code import_tasks: vscode.yml tags: - __vscode # VNC - name: VNC server import_tasks: vnc.yml # NoMachine - name: NoMachine server import_tasks: nomachine.yml when: "'nxserver.service' not in ansible_facts.services" tags: - skip_in_ovami # NoVNC - name: NoVNC server import_tasks: novnc.yml # do reboots if needed - name: Reboot if needed meta: flush_handlers
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/tasks/desktop.yml
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion --- # # Good desktop experience # - name: Configure auto login [1] lineinfile: path: /etc/gdm3/custom.conf state: present line: "AutomaticLoginEnable=true" insertafter: "\\[daemon\\]" notify: reboot - name: Configure auto login [2] lineinfile: path: /etc/gdm3/custom.conf state: present line: "AutomaticLogin=ubuntu" insertafter: "\\[daemon\\]" notify: reboot # disable blank screen - name: Mask sleep targets shell: systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target notify: reboot # disable screen lock - name: Disable screen lock shell: "{{ item }}" with_items: - gsettings set org.gnome.desktop.session idle-delay 0 - gsettings set org.gnome.desktop.screensaver lock-enabled 'false' - gsettings set org.gnome.desktop.lockdown disable-lock-screen 'true' - gsettings set org.gnome.desktop.screensaver idle-activation-enabled 'false' - gsettings set org.gnome.settings-daemon.plugins.power sleep-inactive-battery-timeout 0 become_user: "{{ ansible_user }}" notify: reboot # increase font size - name: Set font size to 125% shell: gsettings set org.gnome.desktop.interface text-scaling-factor 1.25 become_user: "{{ ansible_user }}" # enable dark theme - name: Make it dark shell: gsettings set org.gnome.desktop.interface gtk-theme 'Yaru-dark' become_user: "{{ ansible_user }}" # fix terminal font - name: Fix terminal font shell: "{{ item }}" become_user: "{{ ansible_user }}" with_items: - gsettings set org.gnome.Terminal.Legacy.Profile:/org/gnome/terminal/legacy/profiles:/:$(gsettings get org.gnome.Terminal.ProfilesList default|tr -d \')/ use-system-font false - gsettings set org.gnome.Terminal.Legacy.Profile:/org/gnome/terminal/legacy/profiles:/:$(gsettings get org.gnome.Terminal.ProfilesList default|tr -d \')/ font "Monospace 12" # make terminal semi-transparent - name: Make terminal semi-transparent shell: "{{ item }}" become_user: "{{ ansible_user }}" with_items: - gsettings set org.gnome.Terminal.Legacy.Profile:/org/gnome/terminal/legacy/profiles:/:$(gsettings get org.gnome.Terminal.ProfilesList default|tr -d \')/ background-transparency-percent 12 - gsettings set org.gnome.Terminal.Legacy.Profile:/org/gnome/terminal/legacy/profiles:/:$(gsettings get org.gnome.Terminal.ProfilesList default|tr -d \')/ use-transparent-background true # disable new ubuntu version prompt - name: Disable new ubuntu version prompt lineinfile: path: /etc/update-manager/release-upgrades regexp: "Prompt=.*" line: "Prompt=never" notify: reboot
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/defaults/main.yml
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion --- vnc_password: empty
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/rdesktop/meta/main.yml
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion --- galaxy_info: role_name: rdesktop author: NVIDIA Corporation description: Enables remote desktop access standalone: false dependencies: - { role: system } - { role: nvidia }
NVIDIA-Omniverse/IsaacSim-Automator/src/packer/aws/README.md
# Running packer for AWS Set env vars with credentials: ```sh export AWS_ACCESS_KEY_ID ="..." export AWS_SECRET_ACCESS_KEY ="..." export NGC_API_KEY="..." # optional ``` Alternatively you can pass them as variables in the packer command (`packer -var=varname=value...`). Then launch image builds with: ```sh packer build [-force] [-var=aws_region="us-east-1"] [-var=image_name="..."] [-var=system_user_password="..."] [-var=vnc_password="..."] <folder>/ ``` For example: ```sh packer build -force -var=isaac_image="nvcr.io/nvidia/isaac-sim:2023.1.0-hotfix.1" /app/src/packer/aws/isaac ``` ```sh packer build -force \ -var=aws_region="us-east-1" \ -var=image_name=ovami-test-1 \ -var=system_user_password="nvidia123" \ -var=vnc_password="nvidia123" \ /app/src/packer/aws/ovami ```
NVIDIA-Omniverse/IsaacSim-Automator/src/packer/azure/README.md
# Running packer for Azure See <https://learn.microsoft.com/en-us/azure/virtual-machines/linux/build-image-with-packer> ## 1. Create resource group for packer output ```sh az group create -n isa.packer -l westus3 ``` ## 2. Create Azure service principal ```sh export AZURE_SUBSCRIPTION_ID=`az account list | jq -r .[0].id` az ad sp create-for-rbac \ --role Contributor \ --scopes /subscriptions/$AZURE_SUBSCRIPTION_ID \ --query "{ client_id: appId, client_secret: password, tenant_id: tenant }" ``` ## 3. Build image Set env vars with credentials: ```sh export AZURE_SUBSCRIPTION_ID="..." export AZURE_TENANT_ID="..." export AZURE_SP_CLIENT_ID="..." export AZURE_SP_CLIENT_SECRET="..." export NGC_API_KEY="..." ``` Alternatively you can pass them as variables in the packer command (`packer -var=varname=value...`). Then launch image builds with: ```sh packer build [-var=image_name=...] <folder>/ ``` For example: ```sh packer build isaac/ packer build -var=image_name=my_image_1 isaac/ ```
NVIDIA-Omniverse/IsaacSim-Automator/src/python/config.py
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion from typing import Any, Dict c: Dict[str, Any] = {} # paths c["app_dir"] = "/app" c["state_dir"] = "/app/state" c["results_dir"] = "/app/results" c["uploads_dir"] = "/app/uploads" c["tests_dir"] = "/app/src/tests" c["ansible_dir"] = "/app/src/ansible" c["terraform_dir"] = "/app/src/terraform" # app image name c["app_image_name"] = "isa" # gcp driver # @see https://cloud.google.com/compute/docs/gpus/grid-drivers-table c[ "gcp_driver_url" ] = "https://storage.googleapis.com/nvidia-drivers-us-public/GRID/vGPU16.2/NVIDIA-Linux-x86_64-535.129.03-grid.run" # aws/alicloud driver c["generic_driver_apt_package"] = "nvidia-driver-535-server" # default remote dirs c["default_remote_uploads_dir"] = "/home/ubuntu/uploads" c["default_remote_results_dir"] = "/home/ubuntu/results" c["default_remote_workspace_dir"] = "/home/ubuntu/workspace" # defaults # --isaac-image c["default_isaac_image"] = "nvcr.io/nvidia/isaac-sim:2023.1.1" # --ssh-port c["default_ssh_port"] = 22 # --from-image c["azure_default_from_image"] = False c["aws_default_from_image"] = False # --omniverse-user c["default_omniverse_user"] = "omniverse" # --remote-dir c["default_remote_uploads_dir"] = "/home/ubuntu/uploads" c["default_remote_results_dir"] = "/home/ubuntu/results" # --isaac-instance-type c["aws_default_isaac_instance_type"] = "g5.2xlarge" # str, 1-index in DeployAzureCommand.AZURE_OVKIT_INSTANCE_TYPES c["azure_default_isaac_instance_type"] = "2" c["gcp_default_isaac_instance_type"] = "g2-standard-8" c["alicloud_default_isaac_instance_type"] = "ecs.gn7i-c16g1.4xlarge" # --isaac-gpu-count c["gcp_default_isaac_gpu_count"] = 1 # --region c["alicloud_default_region"] = "us-east-1" # --prefix for the created cloud resources c["default_prefix"] = "isa" # --oige c["default_oige_git_checkpoint"] = "main" # --orbit c["default_orbit_git_checkpoint"] = "devel"
NVIDIA-Omniverse/IsaacSim-Automator/src/python/aws.py
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion """ Utils for AWS """ from src.python.utils import read_meta, shell_command def aws_configure_cli( deployment_name, verbose=False, ): """ Configure AWS CLI for deployment """ meta = read_meta(deployment_name) aws_access_key_id = meta["params"]["aws_access_key_id"] aws_secret_access_key = meta["params"]["aws_secret_access_key"] region = meta["params"]["region"] shell_command( f"aws configure set aws_access_key_id '{aws_access_key_id}'", verbose=verbose, exit_on_error=True, capture_output=True, ) shell_command( f"aws configure set aws_secret_access_key '{aws_secret_access_key}'", verbose=verbose, exit_on_error=True, capture_output=True, ) shell_command( f"aws configure set region '{region}'", verbose=verbose, exit_on_error=True, capture_output=True, ) def aws_stop_instance(instance_id, verbose=False): shell_command( f"aws ec2 stop-instances --instance-ids '{instance_id}'", verbose=verbose, exit_on_error=True, capture_output=True, ) def aws_start_instance(instance_id, verbose=False): shell_command( f"aws ec2 start-instances --instance-ids '{instance_id}'", verbose=verbose, exit_on_error=True, capture_output=True, ) def aws_get_instance_status(instance_id, verbose=False): """ Query instance status Returns: "stopping" | "stopped" | "pending" | "running" """ status = ( shell_command( f"aws ec2 describe-instances --instance-ids '{instance_id}'" + " | jq -r .Reservations[0].Instances[0].State.Name", verbose=verbose, exit_on_error=True, capture_output=True, ) .stdout.decode() .strip() ) return status
NVIDIA-Omniverse/IsaacSim-Automator/src/python/debug.py
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion import debugpy __debug_started = False def debug_start(): global __debug_started if not __debug_started: debugpy.listen(("0.0.0.0", 5678)) print("Waiting for debugger to attach...") debugpy.wait_for_client() print("Debugger attached.") __debug_started = True def debug_break(): debug_start() debugpy.breakpoint()
NVIDIA-Omniverse/IsaacSim-Automator/src/python/ngc.py
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion import pathlib import subprocess SELF_DIR = pathlib.Path(__file__).parent.resolve() def check_ngc_access(ngc_api_key, org="", team="", verbose=False): """ Checks if NGC API key is valid and user has access to DRIVE Sim. Returns: - 0 - all is fine - 100 - invalid api key - 102 - user is not in the team """ proc = subprocess.run( [f"{SELF_DIR}/ngc_check.expect", ngc_api_key, org, team], capture_output=not verbose, timeout=60, ) if proc.returncode not in [0, 100, 101, 102]: raise RuntimeError( f"Error checking NGC API Key. Return code: {proc.returncode}" ) return proc.returncode
NVIDIA-Omniverse/IsaacSim-Automator/src/python/alicloud.py
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion """ Utils for AliCloud """ from src.python.utils import read_meta, shell_command def alicloud_configure_cli( deployment_name, verbose=False, ): """ Configure Aliyun CLI """ meta = read_meta(deployment_name) aliyun_access_key = meta["params"]["aliyun_access_key"] aliyun_secret_key = meta["params"]["aliyun_secret_key"] region = meta["params"]["region"] shell_command( "aliyun configure set " + f"--access-key-id '{aliyun_access_key}'" + f" --access-key-secret '{aliyun_secret_key}'" + f" --region '{region}'", verbose=verbose, exit_on_error=True, capture_output=True, ) def alicloud_start_instance(vm_id, verbose=False): """ Start VM """ shell_command( f"aliyun ecs StartInstance --InstanceId '{vm_id}'", verbose=verbose, exit_on_error=True, capture_output=True, ) def alicloud_stop_instance(vm_id, verbose=False): """ Stop VM """ shell_command( f"aliyun ecs StopInstance --InstanceId '{vm_id}'", verbose=verbose, exit_on_error=True, capture_output=True, ) def alicloud_get_instance_status(vm_id, verbose=False): """ Query VM status Returns: "Stopping" | "Stopped" | "Starting" | "Running" """ status = ( shell_command( f"aliyun ecs DescribeInstances --InstanceIds '[\"{vm_id}\"]'" + " | jq -r .Instances.Instance[0].Status", verbose=verbose, exit_on_error=True, capture_output=True, ) .stdout.decode() .strip() ) return status def alicloud_list_regions( aliyun_access_key, aliyun_secret_key, verbose=False, ): """ List regions """ res = ( shell_command( f"aliyun --access-key-id {aliyun_access_key}" + f" --access-key-secret {aliyun_secret_key}" + " --region cn-beijing ecs DescribeRegions" + " | jq -r '.Regions.Region[].RegionId'", capture_output=True, exit_on_error=True, verbose=verbose, ) .stdout.decode() .strip() ) valid_regions = res.split("\n") return valid_regions
NVIDIA-Omniverse/IsaacSim-Automator/src/python/deployer.py
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion import json import os import re import shlex import sys from pathlib import Path import click from src.python.utils import ( colorize_error, colorize_info, colorize_prompt, colorize_result, read_meta, shell_command, ) from src.python.debug import debug_break # noqa from src.python.ngc import check_ngc_access class Deployer: def __init__(self, params, config): self.tf_outputs = {} self.params = params self.config = config self.existing_behavior = None # save original params so we can recreate command line self.input_params = params.copy() # convert "in_china" self.params["in_china"] = {"yes": True, "no": False, "auto": False}[ self.params["in_china"] ] # create state directory if it doesn't exist os.makedirs(self.config["state_dir"], exist_ok=True) # print complete command line if self.params["debug"]: click.echo(colorize_info("* Command:\n" + self.recreate_command_line())) def __del__(self): # update meta info self.save_meta() def save_meta(self): """ Save command parameters in json file, just in case """ meta_file = ( f"{self.config['state_dir']}/{self.params['deployment_name']}/meta.json" ) data = { "command": self.recreate_command_line(separator=" "), "input_params": self.input_params, "params": self.params, "config": self.config, } Path(meta_file).parent.mkdir(parents=True, exist_ok=True) Path(meta_file).write_text(json.dumps(data, indent=4)) if self.params["debug"]: click.echo(colorize_info(f"* Meta info saved to '{meta_file}'")) def read_meta(self): return read_meta( self.params["deployment_name"], self.params["debug"], ) def recreate_command_line(self, separator=" \\\n"): """ Recreate command line """ command_line = sys.argv[0] for k, v in self.input_params.items(): k = k.replace("_", "-") if isinstance(v, bool): if v: command_line += separator + "--" + k else: not_prefix = "--no-" if k in ["from-image"]: not_prefix = "--not-" command_line += separator + not_prefix + k else: command_line += separator + "--" + k + " " if isinstance(v, str): command_line += "'" + shlex.quote(v) + "'" else: command_line += str(v) return command_line def ask_existing_behavior(self): """ Ask what to do if deployment already exists """ deployment_name = self.params["deployment_name"] existing = self.params["existing"] self.existing_behavior = existing if existing == "ask" and os.path.isfile( f"{self.config['state_dir']}/{deployment_name}/.tfvars" ): self.existing_behavior = click.prompt( text=colorize_prompt( "* Deploymemnt exists, what would you like to do? See --help for details." ), type=click.Choice(["repair", "modify", "replace", "run_ansible"]), default="replace", ) if ( self.existing_behavior == "repair" or self.existing_behavior == "run_ansible" ): # restore params from meta file r = self.read_meta() self.params = r["params"] click.echo( colorize_info( f"* Repairing existing deployment \"{self.params['deployment_name']}\"..." ) ) # update meta info (with new value for existing_behavior) self.save_meta() # destroy existing deployment`` if self.existing_behavior == "replace": debug = self.params["debug"] click.echo(colorize_info("* Deleting existing deployment...")) shell_command( command=f'{self.config["app_dir"]}/destroy "{deployment_name}" --yes' + f' {"--debug" if debug else ""}', verbose=debug, ) # update meta info if deployment was destroyed self.save_meta() def validate_ngc_api_key(self, image, restricted_image=False): """ Check if NGC API key allows to log in and has access to appropriate NGC image @param image: NGC image to check access to @param restricted_image: If image is restricted to specific org/team? """ debug = self.params["debug"] ngc_api_key = self.params["ngc_api_key"] ngc_api_key_check = self.params["ngc_api_key_check"] # extract org and team from the image path r = re.findall( "^nvcr\\.io/([a-z0-9\\-_]+)/([a-z0-9\\-_]+/)?[a-z0-9\\-_]+:[a-z0-9\\-_.]+$", image, ) ngc_org, ngc_team = r[0] ngc_team = ngc_team.rstrip("/") if ngc_org == "nvidia": click.echo( colorize_info( "* Access to docker image can't be checked for NVIDIA org. But you'll be fine. Fingers crossed." ) ) return if debug: click.echo(colorize_info(f'* Will check access to NGC Org: "{ngc_org}"')) click.echo(colorize_info(f'* Will check access to NGC Team: "{ngc_team}"')) if ngc_api_key_check and ngc_api_key != "none": click.echo(colorize_info("* Validating NGC API key... ")) r = check_ngc_access( ngc_api_key=ngc_api_key, org=ngc_org, team=ngc_team, verbose=debug ) if r == 100: raise Exception(colorize_error("NGC API key is invalid.")) # only check access to org/team if restricted image is deployed elif restricted_image and (r == 101 or r == 102): raise Exception( colorize_error( f'NGC API key is valid but you don\'t have access to image "{image}".' ) ) click.echo(colorize_info(("* NGC API Key is valid!"))) def create_tfvars(self, tfvars: dict = {}): """ - Check if deployment with this deployment_name exists and deal with it - Create/update tfvars file Expected values for "existing_behavior" arg: - repair: keep tfvars/tfstate, don't ask for user input - modify: keep tfstate file, update tfvars file with user input - replace: delete tfvars/tfstate files - run_ansible: keep tfvars/tfstate, don't ask for user input, skip terraform steps """ # default values common for all clouds tfvars.update( { "isaac_enabled": self.params["isaac"] if "isaac" in self.params else False, # "isaac_instance_type": self.params["isaac_instance_type"] if "isaac_instance_type" in self.params else "none", # "prefix": self.params["prefix"], "ssh_port": self.params["ssh_port"], # "from_image": self.params["from_image"] if "from_image" in self.params else False, # "deployment_name": self.params["deployment_name"], } ) debug = self.params["debug"] deployment_name = self.params["deployment_name"] # deal with existing deployment: tfvars_file = f"{self.config['state_dir']}/{deployment_name}/.tfvars" tfstate_file = f"{self.config['state_dir']}/{deployment_name}/.tfstate" # tfvars if os.path.exists(tfvars_file): if ( self.existing_behavior == "modify" or self.existing_behavior == "overwrite" ): os.remove(tfvars_file) if debug: click.echo(colorize_info(f'* Deleted "{tfvars_file}"...')) # tfstate if os.path.exists(tfstate_file): if self.existing_behavior == "overwrite": os.remove(tfstate_file) if debug: click.echo(colorize_info(f'* Deleted "{tfstate_file}"...')) # create tfvars file if ( self.existing_behavior == "modify" or self.existing_behavior == "overwrite" or not os.path.exists(tfvars_file) ): self._write_tfvars_file(path=tfvars_file, tfvars=tfvars) def _write_tfvars_file(self, path: str, tfvars: dict): """ Write tfvars file """ debug = self.params["debug"] if debug: click.echo(colorize_info(f'* Created tfvars file "{path}"')) # create <dn>/ directory if it doesn't exist Path(path).parent.mkdir(parents=True, exist_ok=True) with open(path, "w") as f: for key, value in tfvars.items(): # convert booleans to strings if isinstance(value, bool): value = { True: "true", False: "false", }[value] # format key names key = key.replace("-", "_") # write values if isinstance(value, str): value = value.replace('"', '\\"') f.write(f'{key} = "{value}"\n') elif isinstance(value, list): f.write(f"{key} = " + str(value).replace("'", '"') + "\n") else: f.write(f"{key} = {value}\n") def create_ansible_inventory(self, write: bool = True): """ Create Ansible inventory, return it as text Write to file if write=True """ debug = self.params["debug"] deployment_name = self.params["deployment_name"] ansible_vars = self.params.copy() # add config ansible_vars["config"] = self.config # get missing values from terraform for k in [ "isaac_ip", "ovami_ip", "cloud", ]: if k not in self.params or ansible_vars[k] is None: ansible_vars[k] = self.tf_output(k) # convert booleans to ansible format ansible_booleans = {True: "true", False: "false"} for k, v in ansible_vars.items(): if isinstance(v, bool): ansible_vars[k] = ansible_booleans[v] template = Path(f"{self.config['ansible_dir']}/inventory.template").read_text() res = template.format(**ansible_vars) # write to file if write: inventory_file = f"{self.config['state_dir']}/{deployment_name}/.inventory" Path(inventory_file).parent.mkdir(parents=True, exist_ok=True) # create dir Path(inventory_file).write_text(res) # write file if debug: click.echo( colorize_info( f'* Created Ansible inventory file "{inventory_file}"' ) ) return res def initialize_terraform(self, cwd: str): """ Initialize Terraform via shell command cwd: directory where terraform scripts are located """ debug = self.params["debug"] shell_command( f"terraform init -upgrade -no-color -input=false {' > /dev/null' if not debug else ''}", verbose=debug, cwd=cwd, ) def run_terraform(self, cwd: str): """ Apply Terraform via shell command cwd: directory where terraform scripts are located """ debug = self.params["debug"] deployment_name = self.params["deployment_name"] shell_command( "terraform apply -auto-approve " + f"-state={self.config['state_dir']}/{deployment_name}/.tfstate " + f"-var-file={self.config['state_dir']}/{deployment_name}/.tfvars", cwd=cwd, verbose=debug, ) def export_ssh_key(self): """ Export SSH key from Terraform state """ debug = self.params["debug"] deployment_name = self.params["deployment_name"] shell_command( f"terraform output -state={self.config['state_dir']}/{deployment_name}/.tfstate -raw ssh_key" + f" > {self.config['state_dir']}/{deployment_name}/key.pem && " + f"chmod 0600 {self.config['state_dir']}/{deployment_name}/key.pem", verbose=debug, ) def run_ansible(self, playbook_name: str, cwd: str): """ Run Ansible playbook via shell command """ debug = self.params["debug"] deployment_name = self.params["deployment_name"] shell_command( f"ansible-playbook -i {self.config['state_dir']}/{deployment_name}/.inventory " + f"{playbook_name}.yml {'-vv' if self.params['debug'] else ''}", cwd=cwd, verbose=debug, ) def run_all_ansible(self): # run ansible for isaac if "isaac" in self.params and self.params["isaac"]: click.echo(colorize_info("* Running Ansible for Isaac Sim...")) self.run_ansible(playbook_name="isaac", cwd=f"{self.config['ansible_dir']}") # run ansible for ovami # todo: move to ./deploy-aws if "ovami" in self.params and self.params["ovami"]: click.echo(colorize_info("* Running Ansible for OV AMI...")) self.run_ansible(playbook_name="ovami", cwd=f"{self.config['ansible_dir']}") def tf_output(self, key: str, default: str = ""): """ Read Terraform output. Cache read values in self._tf_outputs. """ if key not in self.tf_outputs: debug = self.params["debug"] deployment_name = self.params["deployment_name"] r = shell_command( f"terraform output -state='{self.config['state_dir']}/{deployment_name}/.tfstate' -raw '{key}'", capture_output=True, exit_on_error=False, verbose=debug, ) if r.returncode == 0: self.tf_outputs[key] = r.stdout.decode() else: if self.params["debug"]: click.echo( colorize_error( f"* Warning: Terraform output '{key}' cannot be read." ), err=True, ) self.tf_outputs[key] = default # update meta file to reflect tf outputs self.save_meta() return self.tf_outputs[key] def upload_user_data(self): shell_command( f'./upload "{self.params["deployment_name"]}" ' + f'{"--debug" if self.params["debug"] else ""}', cwd=self.config["app_dir"], verbose=self.params["debug"], exit_on_error=True, capture_output=False, ) # generate ssh connection command for the user def ssh_connection_command(self, ip: str): r = f"ssh -i state/{self.params['deployment_name']}/key.pem " r += f"-o StrictHostKeyChecking=no ubuntu@{ip}" if self.params["ssh_port"] != 22: r += f" -p {self.params['ssh_port']}" return r def output_deployment_info(self, extra_text: str = "", print_text=True): """ Print connection info for the user Save info to file (_state_dir_/_deployment_name_/info.txt) """ isaac = "isaac" in self.params and self.params["isaac"] ovami = "ovami" in self.params and self.params["ovami"] vnc_password = self.params["vnc_password"] deployment_name = self.params["deployment_name"] # templates nomachine_instruction = f"""* To connect to __app__ via NoMachine: 0. Download NoMachine client at https://downloads.nomachine.com/, install and launch it. 1. Click "Add" button. 2. Enter Host: "__ip__". 3. In "Configuration" > "Use key-based authentication with a key you provide", select file "state/{deployment_name}/key.pem". 4. Click "Connect" button. 5. Enter "ubuntu" as a username when prompted. """ vnc_instruction = f"""* To connect to __app__ via VNC: - IP: __ip__ - Port: 5900 - Password: {vnc_password}""" nonvc_instruction = f"""* To connect to __app__ via noVNC: 1. Open http://__ip__:6080/vnc.html?host=__ip__&port=6080 in your browser. 2. Click "Connect" and use password \"{vnc_password}\"""" # print connection info instructions_file = f"{self.config['state_dir']}/{deployment_name}/info.txt" instructions = "" if isaac: instructions += f"""{'*' * (29+len(self.tf_output('isaac_ip')))} * Isaac Sim is deployed at {self.tf_output('isaac_ip')} * {'*' * (29+len(self.tf_output('isaac_ip')))} * To connect to Isaac Sim via SSH: {self.ssh_connection_command(self.tf_output('isaac_ip'))} {nonvc_instruction} {nomachine_instruction}""".replace( "__app__", "Isaac Sim" ).replace( "__ip__", self.tf_output("isaac_ip") ) # todo: move to ./deploy-aws if ovami: instructions += f"""\n * OV AMI is deployed at {self.tf_output('ovami_ip')} * To connect to OV AMI via SSH: {self.ssh_connection_command(self.tf_output('ovami_ip'))} * To connect to OV AMI via NICE DCV: - IP: __ip__ {vnc_instruction} {nomachine_instruction} """.replace( "__app__", "OV AMI" ).replace( "__ip__", self.tf_output("ovami_ip") ) # extra text if len(extra_text) > 0: instructions += extra_text + "\n" # print instructions for the user if print_text: click.echo(colorize_result("\n" + instructions)) # create <dn>/ directory if it doesn't exist Path(instructions_file).parent.mkdir(parents=True, exist_ok=True) # write file Path(instructions_file).write_text(instructions) return instructions
NVIDIA-Omniverse/IsaacSim-Automator/src/python/utils.py
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion """ CLI Utils """ import json import os import subprocess from glob import glob from pathlib import Path import click from src.python.config import c as config def colorize_prompt(text): return click.style(text, fg="bright_cyan", italic=True) def colorize_error(text): return click.style(text, fg="bright_red", italic=True) def colorize_info(text): return click.style(text, fg="bright_magenta", italic=True) def colorize_result(text): return click.style(text, fg="bright_green", italic=True) def shell_command( command, verbose=False, cwd=None, exit_on_error=True, capture_output=False ): """ Execute shell command, print it if debug is enabled """ if verbose: if cwd is not None: click.echo(colorize_info(f"* Running `(cd {cwd} && {command})`...")) else: click.echo(colorize_info(f"* Running `{command}`...")) res = subprocess.run( command, shell=True, cwd=cwd, capture_output=capture_output, ) if res.returncode == 0: if verbose and res.stdout is not None: click.echo(res.stdout.decode()) elif exit_on_error: if res.stderr is not None: click.echo( colorize_error(f"Error: {res.stderr.decode()}"), err=True, ) exit(1) return res def deployments(): """List existing deployments by name""" state_dir = config["state_dir"] deployments = sorted( [ os.path.basename(os.path.dirname(d)) for d in glob(os.path.join(state_dir, "*/")) ] ) return deployments def read_meta(deployment_name: str, verbose: bool = False): """ Read metadata from json file """ meta_file = f"{config['state_dir']}/{deployment_name}/meta.json" if os.path.isfile(meta_file): data = json.loads(Path(meta_file).read_text()) if verbose: click.echo(colorize_info(f"* Meta info loaded from '{meta_file}'")) return data raise Exception(f"Meta file '{meta_file}' not found") def read_tf_output(deployment_name, output, verbose=False): """ Read terraform output from tfstate file """ return ( shell_command( f"terraform output -state={config['state_dir']}/{deployment_name}/.tfstate -raw {output}", capture_output=True, exit_on_error=False, verbose=verbose, ) .stdout.decode() .strip() ) def format_app_name(app_name): """ Format app name for user output """ formatted = { "isaac": "Isaac Sim", "ovami": "OV AMI", } if app_name in formatted: return formatted[app_name] return app_name def format_cloud_name(cloud_name): """ Format cloud name for user output """ formatted = { "aws": "AWS", "azure": "Azure", "gcp": "GCP", "alicloud": "Alibaba Cloud", } if cloud_name in formatted: return formatted[cloud_name] return cloud_name def gcp_login(verbose=False): """ Log into GCP """ # detect if we need to re-login click.echo(colorize_info("* Checking GCP login status..."), nl=False) res = shell_command( "gcloud auth application-default print-access-token 2>&1 > /dev/null", verbose=verbose, exit_on_error=False, capture_output=True, ) logged_in = res.returncode == 0 if logged_in: click.echo(colorize_info(" logged in!")) if not logged_in: click.echo(colorize_info(" not logged in")) shell_command( "gcloud auth application-default login --no-launch-browser --disable-quota-project --verbosity none", verbose=verbose, )
NVIDIA-Omniverse/IsaacSim-Automator/src/python/azure.py
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion """ Utils for Azure """ import click from src.python.utils import colorize_info, read_meta, shell_command def azure_login(verbose=False): """ Log into Azure """ # detect if we need to re-login logged_in = ( '"Enabled"' == shell_command( "az account show --query state", verbose=verbose, exit_on_error=False, capture_output=True, ) .stdout.decode() .strip() ) if not logged_in: click.echo(colorize_info("* Logging into Azure...")) shell_command("az login --use-device-code", verbose=verbose) def azure_stop_instance(vm_id, verbose=False): shell_command( f"az vm deallocate --ids {vm_id}", verbose=verbose, exit_on_error=True, capture_output=False, ) def azure_start_instance(vm_id, verbose=False): shell_command( f"az vm start --ids {vm_id}", verbose=verbose, exit_on_error=True, capture_output=False, )
NVIDIA-Omniverse/IsaacSim-Automator/src/python/deploy_command.py
# region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion """ Base deploy- command """ import os import re import click import randomname from pwgen import pwgen from src.python.config import c as config from src.python.debug import debug_break # noqa from src.python.utils import colorize_error, colorize_prompt class DeployCommand(click.core.Command): """ Defines common cli options for "deploy-*" commands. """ @staticmethod def isaac_callback(ctx, param, value): """ Called after --isaac option is parsed """ # disable isaac instance type selection if isaac is disabled if value is False: for p in ctx.command.params: if p.name.startswith("isaac"): p.prompt = None return value @staticmethod def deployment_name_callback(ctx, param, value): # validate if not re.match("^[a-z0-9\\-]{1,32}$", value): raise click.BadParameter( colorize_error( "Only lower case letters, numbers and '-' are allowed." + f" Length should be between 1 and 32 characters ({len(value)} provided)." ) ) return value @staticmethod def ngc_api_key_callback(ctx, param, value): """ Validate NGC API key """ # fix click bug if value is None: return value # allow "none" as a special value if "none" == value: return value # check if it contains what's allowed if not re.match("^[A-Za-z0-9]{32,}$", value): raise click.BadParameter( colorize_error("Key contains invalid characters or too short.") ) return value @staticmethod def ngc_image_callback(ctx, param, value): """ Called after parsing --isaac-image options are parsed """ # ignore case value = value.lower() if not re.match( "^nvcr\\.io/[a-z0-9\\-_]+/([a-z0-9\\-_]+/)?[a-z0-9\\-_]+:[a-z0-9\\-_.]+$", value, ): raise click.BadParameter( colorize_error( "Invalid image name. " + "Expected: nvcr.io/<org>/[<team>/]<image>:<tag>" ) ) return value @staticmethod def oige_callback(ctx, param, value): """ Called after parsing --oige option """ if "" == value: return config["default_oige_git_checkpoint"] return value @staticmethod def orbit_callback(ctx, param, value): """ Called after parsing --orbit option """ if "" == value: return config["default_orbit_git_checkpoint"] return value def param_index(self, param_name): """ Return index of parameter with given name. Useful for inserting new parameters at a specific position. """ return list( filter( lambda param: param[1].name == param_name, enumerate(self.params), ) )[0][0] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # add common options self.params.insert( len(self.params), click.core.Option( ("--debug/--no-debug",), default=False, show_default=True, help="Enable debug output.", ), ) # --prefix self.params.insert( len(self.params), click.core.Option( ("--prefix",), default=config["default_prefix"], show_default=True, help="Prefix for all cloud resources.", ), ) # --from-image/--not-from-image self.params.insert( len(self.params), click.core.Option( ("--from-image/--not-from-image",), default=False, show_default=True, help="Deploy from pre-built image, from bare OS otherwise.", ), ) # --in-china self.params.insert( len(self.params), click.core.Option( ("--in-china",), type=click.Choice(["auto", "yes", "no"]), prompt=False, default="auto", show_default=True, help="Is deployment in China? (Local mirrors will be used.)", ), ) self.params.insert( len(self.params), click.core.Option( ("--deployment-name", "--dn"), prompt=colorize_prompt( '* Deployment Name (lower case letters, numbers and "-")' ), default=randomname.get_name, callback=DeployCommand.deployment_name_callback, show_default="<randomly generated>", help="Name of the deployment. Used to identify the created cloud resources and files.", ), ) self.params.insert( len(self.params), click.core.Option( ("--existing",), type=click.Choice( ["ask", "repair", "modify", "replace", "run_ansible"] ), default="ask", show_default=True, help="""What to do if deployment already exists: \n* 'repair' will try to fix broken deployment without applying new user parameters. \n* 'modify' will update user selected parameters and attempt to update existing cloud resources. \n* 'replace' will attempt to delete old deployment's cloud resources first. \n* 'run_ansible' will re-run Ansible playbooks.""", ), ) self.params.insert( len(self.params), click.core.Option( ("--isaac/--no-isaac",), default=True, show_default="yes", prompt=colorize_prompt("* Deploy Isaac Sim?"), callback=DeployCommand.isaac_callback, help="Deploy Isaac Sim (BETA)?", ), ) self.params.insert( len(self.params), click.core.Option( ("--isaac-image",), default=config["default_isaac_image"], prompt=colorize_prompt("* Isaac Sim docker image"), show_default=True, callback=DeployCommand.ngc_image_callback, help="Isaac Sim docker image to use.", ), ) # --oige help = ( "Install Omni Isaac Gym Envs? Valid values: 'no', " + "or <git ref in github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs>" ) self.params.insert( len(self.params), click.core.Option( ("--oige",), help=help, default="main", show_default=True, prompt=colorize_prompt("* " + help), callback=DeployCommand.oige_callback, ), ) # --orbit help = ( "[EXPERIMENTAL] Install Isaac Sim Orbit? Valid values: 'no', " + "or <git ref in github.com/NVIDIA-Omniverse/orbit>" ) self.params.insert( len(self.params), click.core.Option( ("--orbit",), help=help, default="no", show_default=True, prompt=colorize_prompt("* " + help), callback=DeployCommand.orbit_callback, ), ) self.params.insert( len(self.params), click.core.Option( ("--ngc-api-key",), type=str, prompt=colorize_prompt( "* NGC API Key (can be obtained at https://ngc.nvidia.com/setup/api-key)" ), default=os.environ.get("NGC_API_KEY", ""), show_default='"NGC_API_KEY" environment variable', help="NGC API Key (can be obtained at https://ngc.nvidia.com/setup/api-key)", callback=DeployCommand.ngc_api_key_callback, ), ) self.params.insert( len(self.params), click.core.Option( ("--ngc-api-key-check/--no-ngc-api-key-check",), default=True, help="Skip NGC API key validity check.", ), ) self.params.insert( len(self.params), click.core.Option( ("--vnc-password",), default=lambda: pwgen(10), help="Password for VNC access to DRIVE Sim/Isaac Sim/etc.", show_default="<randomly generated>", ), ) self.params.insert( len(self.params), click.core.Option( ("--system-user-password",), default=lambda: pwgen(10), help="System user password", show_default="<randomly generated>", ), ) self.params.insert( len(self.params), click.core.Option( ("--ssh-port",), default=config["default_ssh_port"], help="SSH port for connecting to the deployed machines.", show_default=True, ), ) # --upload/--no-upload self.params.insert( len(self.params), click.core.Option( ("--upload/--no-upload",), prompt=False, default=True, show_default=True, help=f"Upload user data from \"{config['uploads_dir']}\" to cloud " + f"instances (to \"{config['default_remote_uploads_dir']}\")?", ), ) default_nucleus_admin_password = pwgen(10) # --omniverse-user self.params.insert( len(self.params), click.core.Option( ("--omniverse-user",), default=config["default_omniverse_user"], help="Username for accessing content on the Nucleus server.", show_default=True, ), ) # --omniverse-password self.params.insert( len(self.params), click.core.Option( ("--omniverse-password",), default=default_nucleus_admin_password, help="Password for accessing content on the Nucleus server.", show_default="<randomly generated>", ), )
NVIDIA-Omniverse/IsaacSim-Automator/src/python/ngc.test.py
#!/usr/bin/env python3 # region copyright # Copyright 2023 NVIDIA Corporation # # Licensed 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. # endregion import os import unittest from src.python.ngc import check_ngc_access class Test_NGC_Key_Validation(unittest.TestCase): INVALID_KEY = "__invalid__" VALID_KEY = os.environ.get("NGC_API_KEY", "__none__") def test_invalid_key(self): """Test invalid key""" r = check_ngc_access(self.INVALID_KEY) self.assertEqual(r, 100) def test_valid_key(self): """Test valid key (should be set in NGC_API_KEY env var)""" if "__none__" == self.VALID_KEY: self.skipTest("No NGC_API_KEY env var set") return r = check_ngc_access(self.VALID_KEY) self.assertEqual(r, 0) if __name__ == "__main__": unittest.main()
NVIDIA-Omniverse/IsaacSim-Automator/src/tests/deployer.test.py
#!/usr/bin/env python3 import unittest from src.python.config import c from src.python.deployer import Deployer from pathlib import Path class Test_Deployer(unittest.TestCase): def setUp(self): self.config = c self.config["state_dir"] = f"{c['tests_dir']}/res/state" self.deployer = Deployer( params={ "debug": False, "prefix": "isa", "from_image": False, "deployment_name": "test-1", "existing": "ask", "region": "us-east-1", "isaac": True, "isaac_instance_type": "g5.2xlarge", "isaac_image": "nvcr.io/nvidia/isaac-sim:2022.2.0", "ngc_api_key": "__ngc_api_key__", "ngc_api_key_check": True, "vnc_password": "__vnc_password__", "omniverse_user": "ovuser", "omniverse_password": "__omniverse_password__", "ssh_port": 22, "upload": True, "aws_access_key_id": "__aws_access_key_id__", "aws_secret_access_key": "__aws_secret_access_key__", }, config=self.config, ) def tearDown(self): self.deployer = None def test_output_deployment_info(self): self.deployer.output_deployment_info(print_text=False) file_generated = f"{self.config['state_dir']}/test-1/info.txt" file_expected = f"{self.config['state_dir']}/test-1/info.expected.txt" file_generated = Path(file_generated).read_text() file_expected = Path(file_expected).read_text() self.assertEqual(file_generated, file_expected) if __name__ == "__main__": unittest.main()
NVIDIA-Omniverse/IsaacSim-Automator/src/tests/res/state/test-1/info.expected.txt
**************************************** * Isaac Sim is deployed at 11.22.33.44 * **************************************** * To connect to Isaac Sim via SSH: ssh -i state/test-1/key.pem -o StrictHostKeyChecking=no [email protected] * To connect to Isaac Sim via noVNC: 1. Open http://11.22.33.44:6080/vnc.html?host=11.22.33.44&port=6080 in your browser. 2. Click "Connect" and use password "__vnc_password__" * To connect to Isaac Sim via NoMachine: 0. Download NoMachine client at https://downloads.nomachine.com/, install and launch it. 1. Click "Add" button. 2. Enter Host: "11.22.33.44". 3. In "Configuration" > "Use key-based authentication with a key you provide", select file "state/test-1/key.pem". 4. Click "Connect" button. 5. Enter "ubuntu" as a username when prompted.
NVIDIA-Omniverse/IsaacSim-Automator/src/tests/res/state/test-1/meta.json
{ "command": "src/tests/deployer.test.py --no-debug --prefix 'isa' --no-from-image --deployment-name 'test-1' --existing 'ask' --region 'us-east-1' --isaac --isaac-instance-type 'g5.2xlarge' --isaac-image 'nvcr.io/nvidia/isaac-sim:2022.2.0' --ngc-api-key '__ngc_api_key__' --ngc-api-key-check --vnc-password '__vnc_password__' --omniverse-user 'ovuser' --omniverse-password '__omniverse_password__' --ssh-port 22 --upload --aws-access-key-id '__aws_access_key_id__' --aws-secret-access-key '__aws_secret_access_key__'", "input_params": { "debug": false, "prefix": "isa", "from_image": false, "deployment_name": "test-1", "existing": "ask", "region": "us-east-1", "isaac": true, "isaac_instance_type": "g5.2xlarge", "isaac_image": "nvcr.io/nvidia/isaac-sim:2022.2.0", "ngc_api_key": "__ngc_api_key__", "ngc_api_key_check": true, "vnc_password": "__vnc_password__", "omniverse_user": "ovuser", "omniverse_password": "__omniverse_password__", "ssh_port": 22, "upload": true, "aws_access_key_id": "__aws_access_key_id__", "aws_secret_access_key": "__aws_secret_access_key__" }, "params": { "debug": false, "prefix": "isa", "from_image": false, "deployment_name": "test-1", "existing": "ask", "region": "us-east-1", "isaac": true, "isaac_instance_type": "g5.2xlarge", "isaac_image": "nvcr.io/nvidia/isaac-sim:2022.2.0", "ngc_api_key": "__ngc_api_key__", "ngc_api_key_check": true, "vnc_password": "__vnc_password__", "omniverse_user": "ovuser", "omniverse_password": "__omniverse_password__", "ssh_port": 22, "upload": true, "aws_access_key_id": "__aws_access_key_id__", "aws_secret_access_key": "__aws_secret_access_key__" }, "config": { "app_dir": "/app", "state_dir": "/app/src/tests/res/state", "results_dir": "/app/results", "uploads_dir": "/app/uploads", "tests_dir": "/app/src/tests", "ansible_dir": "/app/src/ansible", "terraform_dir": "/app/src/terraform", "app_image_name": "isa", "default_isaac_image": "nvcr.io/nvidia/isaac-sim:2023.1.0", "default_ssh_port": 22, "azure_default_from_image": false, "aws_default_from_image": false, "default_omniverse_user": "omniverse", "default_remote_uploads_dir": "/home/ubuntu/uploads", "default_remote_results_dir": "/home/ubuntu/results", "aws_default_isaac_instance_type": "g5.2xlarge", "azure_default_isaac_instance_type": "2", "gcp_default_isaac_instance_type": "g2-standard-8", "gcp_default_isaac_gpu_count": 1, "default_prefix": "isa" } }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/aws/main.tf
terraform { required_version = ">= 1.3.5" required_providers { aws = { source = "hashicorp/aws" version = "~> 4.41" } } } provider "aws" { region = var.region access_key = var.aws_access_key_id secret_key = var.aws_secret_access_key default_tags { tags = { Deployment = "${var.deployment_name}" } } } module "common" { source = "./common" prefix = "${var.prefix}.${var.deployment_name}" region = var.region } module "vpc" { source = "./vpc" prefix = "${var.prefix}.${var.deployment_name}" region = var.region } module "isaac" { source = "./isaac" prefix = "${var.prefix}.${var.deployment_name}.isaac" count = var.isaac_enabled ? 1 : 0 keypair_id = module.common.aws_key_pair_id instance_type = var.isaac_instance_type from_image = var.from_image region = var.region ssh_port = var.ssh_port deployment_name = var.deployment_name prebuilt_ami_name = "${var.prefix}.packer.isaac_image.*" iam_instance_profile = null vpc = { id = module.vpc.vpc.id cidr_block = module.vpc.vpc.cidr_block } } module "ovami" { source = "./ovami" prefix = "${var.prefix}.${var.deployment_name}.ovami" count = var.ovami_enabled ? 1 : 0 keypair_id = module.common.aws_key_pair_id ssh_port = var.ssh_port deployment_name = var.deployment_name vpc = { id = module.vpc.vpc.id cidr_block = module.vpc.vpc.cidr_block } }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/aws/variables.tf
# prefix for created resources and tags # full name looks like <prefix>.<deployment_name>.<app_name>.<resource_type> variable "prefix" { default = "isa" type = string } variable "deployment_name" { type = string } variable "region" { type = string } variable "ovami_enabled" { type = bool } variable "from_image" { default = false type = bool } variable "aws_access_key_id" { type = string } variable "aws_secret_access_key" { type = string } variable "ssh_port" { type = number } variable "isaac_enabled" { type = bool } variable "isaac_instance_type" { type = string }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/aws/outputs.tf
output "ssh_key" { value = module.common.ssh_key.private_key_pem sensitive = true } output "cloud" { value = "aws" } output "isaac_ip" { value = var.isaac_enabled ? module.isaac[0].public_ip : "NA" } output "isaac_vm_id" { value = try(var.isaac_enabled ? module.isaac[0].vm_id : "NA", "NA") } output "ovami_ip" { value = var.ovami_enabled ? module.ovami[0].public_ip : "NA" }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/aws/vpc/main.tf
resource "aws_vpc" "vpc" { cidr_block = var.vpc_cidr_block enable_dns_hostnames = true tags = { Name = "${var.prefix}.vpc" } } resource "aws_internet_gateway" "vpc_gateway" { vpc_id = aws_vpc.vpc.id tags = { Name = "${var.prefix}.vpc_gateway" } } resource "aws_default_route_table" "vpc_route_table" { default_route_table_id = aws_vpc.vpc.default_route_table_id route { cidr_block = "0.0.0.0/0" gateway_id = aws_internet_gateway.vpc_gateway.id } timeouts { create = "5m" update = "5m" } tags = { Name = "${var.prefix}.vpc_route_table" } }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/aws/vpc/variables.tf
variable "region" { description = "Region we're creating resources in." type = string } variable "vpc_cidr_block" { description = "CIDR block for the entire VPC. Will be split into /24 subnets." default = "10.1.0.0/16" type = string } variable "prefix" { description = "Prefix for all resources this module creates." type = string }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/aws/vpc/outputs.tf
output "vpc" { description = "Created VPC" value = { id = aws_vpc.vpc.id cidr_block = aws_vpc.vpc.cidr_block } }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/aws/isaac/main.tf
# query availability zones where # we can launch instances of type required data "aws_ec2_instance_type_offerings" "zones" { filter { name = "instance-type" values = [var.instance_type] } location_type = "availability-zone" } # create a subnet for the isaac instance resource "aws_subnet" "subnet" { # get a /24 block from vpc cidr cidr_block = cidrsubnet(var.vpc.cidr_block, 8, 3) availability_zone = try(sort(data.aws_ec2_instance_type_offerings.zones.locations)[0], "not-available") vpc_id = var.vpc.id map_public_ip_on_launch = true tags = { Name = "${var.prefix}.subnet" } } # instance resource "aws_instance" "instance" { ami = data.aws_ami.ami.id instance_type = var.instance_type key_name = var.keypair_id vpc_security_group_ids = [aws_security_group.sg.id] subnet_id = aws_subnet.subnet.id iam_instance_profile = var.iam_instance_profile root_block_device { volume_type = "gp3" volume_size = "256" # GB delete_on_termination = true tags = { Name = "${var.prefix}.root_ebs" Deployment = "${var.deployment_name}" } } tags = { Name = "${var.prefix}.vm" } } # elastic ip resource "aws_eip" "eip" { instance = aws_instance.instance.id tags = { Name = "${var.prefix}.eip" } }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/aws/isaac/variables.tf
variable "prefix" { type = string } variable "keypair_id" { type = string } variable "instance_type" { type = string } variable "region" { type = string } variable "from_image" { default = true type = bool } variable "vpc" { type = object({ id = string, cidr_block = string, }) } variable "iam_instance_profile" { default = null type = string } variable "deployment_name" { type = string } # amis: # base - used when from_image is *false* variable "base_ami_name" { default = "ubuntu/images/hvm-ssd/ubuntu-*-20.04-amd64-server-*" } # prebuilt - used when from_image is *true* variable "prebuilt_ami_name" { default = "isa.packer.isaac_image.*" } variable "ssh_port" { type = number }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/aws/isaac/security.tf
# security group for isaac resource "aws_security_group" "sg" { name = "${var.prefix}.sg" vpc_id = var.vpc.id tags = { Name = "${var.prefix}.sg" } # ssh ingress { from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } # nomachine ingress { from_port = 4000 to_port = 4000 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } ingress { from_port = 4000 to_port = 4000 protocol = "udp" cidr_blocks = ["0.0.0.0/0"] } # vnc ingress { from_port = 5900 to_port = 5900 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } # novnc ingress { from_port = 6080 to_port = 6080 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } # allow outbound traffic egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] } } # custom ssh port resource "aws_security_group_rule" "custom_ssh" { count = var.ssh_port != 22 ? 1 : 0 type = "ingress" security_group_id = aws_security_group.sg.id from_port = var.ssh_port to_port = var.ssh_port protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/aws/isaac/outputs.tf
output "public_ip" { value = aws_eip.eip.public_ip } output "vm_id" { value = aws_instance.instance.id }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/aws/isaac/ami.tf
# finds available base image data "aws_ami" "ami" { most_recent = true filter { name = "name" values = [ var.from_image ? var.prebuilt_ami_name : var.base_ami_name ] } filter { name = "virtualization-type" values = ["hvm"] } owners = [ "565494100184", # NVIDIA "099720109477", # Canonical "self" # Customer ] }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/aws/ovami/main.tf
# query availability zones where # we can launch instances of type required data "aws_ec2_instance_type_offerings" "zones" { filter { name = "instance-type" values = [var.instance_type] } location_type = "availability-zone" } # create a subnet for the ovami instance resource "aws_subnet" "subnet" { # get a /24 block from vpc cidr cidr_block = cidrsubnet(var.vpc.cidr_block, 8, 5) availability_zone = try(sort(data.aws_ec2_instance_type_offerings.zones.locations)[0], "not-available") vpc_id = var.vpc.id map_public_ip_on_launch = true tags = { Name = "${var.prefix}.subnet" } } # instance resource "aws_instance" "instance" { ami = data.aws_ami.ami.id instance_type = var.instance_type key_name = var.keypair_id vpc_security_group_ids = [aws_security_group.sg.id] subnet_id = aws_subnet.subnet.id root_block_device { volume_type = "gp3" volume_size = "256" # GB delete_on_termination = true tags = { Name = "${var.prefix}.root_ebs" Deployment = "${var.deployment_name}" } } tags = { Name = "${var.prefix}.vm" } } # elastic ip resource "aws_eip" "eip" { instance = aws_instance.instance.id tags = { Name = "${var.prefix}.eip" } }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/aws/ovami/variables.tf
variable "prefix" { type = string } variable "keypair_id" { type = string } variable "instance_type" { default = "g5.4xlarge" type = string } variable "region" { default = "us-east-1" type = string } variable "vpc" { type = object({ id = string, cidr_block = string, }) } variable "base_ami_name" { default = "ubuntu/images/hvm-ssd/ubuntu-*-20.04-amd64-server-*" } variable "ssh_port" { default = 22 type = number } variable "deployment_name" { type = string }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/aws/ovami/security.tf
# security group for ovami resource "aws_security_group" "sg" { name = "${var.prefix}.sg" vpc_id = var.vpc.id tags = { Name = "${var.prefix}.sg" } # ssh ingress { from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } # nomachine ingress { from_port = 4000 to_port = 4000 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } ingress { from_port = 4000 to_port = 4000 protocol = "udp" cidr_blocks = ["0.0.0.0/0"] } # dcv ingress { from_port = 8443 to_port = 8443 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } ingress { from_port = 8443 to_port = 8443 protocol = "udp" cidr_blocks = ["0.0.0.0/0"] } # vnc ingress { from_port = 5900 to_port = 5900 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } # novnc ingress { from_port = 6080 to_port = 6080 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } # allow outbound traffic egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] } } # custom ssh port resource "aws_security_group_rule" "custom_ssh" { count = var.ssh_port != 22 ? 1 : 0 type = "ingress" security_group_id = aws_security_group.sg.id from_port = var.ssh_port to_port = var.ssh_port protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/aws/ovami/outputs.tf
output "public_ip" { value = aws_eip.eip.public_ip }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/aws/ovami/ami.tf
# finds available base image data "aws_ami" "ami" { most_recent = true filter { name = "name" values = [ var.base_ami_name ] } filter { name = "virtualization-type" values = ["hvm"] } owners = [ "099720109477", # Canonical "self" # Customer ] }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/aws/common/main.tf
# ssh key resource "tls_private_key" "ssh_key" { algorithm = "RSA" rsa_bits = 4096 } # keypair resource "aws_key_pair" "keypair" { key_name = "${var.prefix}.keypair" public_key = tls_private_key.ssh_key.public_key_openssh tags = { Name = "${var.prefix}.keypair" } }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/aws/common/variables.tf
variable "prefix" { # prefix for all resources and tags created by this module type = string } variable "ssh_key" { default = null } variable "region" { type = string }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/aws/common/outputs.tf
output "ssh_key" { value = tls_private_key.ssh_key } output "aws_key_pair_id" { value = aws_key_pair.keypair.id }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/gcp/main.tf
terraform { required_version = ">= 1.3.5" required_providers { google = { source = "hashicorp/google" version = ">= 4.57.0" } } } provider "google" { project = var.project zone = var.zone } module "isaac" { source = "./ovkit" count = var.isaac_enabled ? 1 : 0 isaac_enabled = true prefix = "${var.prefix}-${var.deployment_name}-isaac" deployment_name = var.deployment_name public_key_openssh = tls_private_key.ssh_key.public_key_openssh instance_type = var.isaac_instance_type gpu_count = var.isaac_gpu_count gpu_type = var.isaac_gpu_type ssh_port = var.ssh_port }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/gcp/variables.tf
# prefix for created resources and tags # full name looks like <prefix>.<deployment_name>.<app_name>.<resource_type> variable "prefix" { type = string } variable "deployment_name" { type = string } variable "from_image" { default = false type = bool } variable "ssh_port" { type = number } variable "zone" { type = string } variable "project" { type = string } variable "isaac_enabled" { default = false type = bool } variable "isaac_instance_type" { type = string } variable "isaac_gpu_count" { type = number } variable "isaac_gpu_type" { # "nvidia-tesla-t4" or "nvidia-l4" type = string }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/gcp/common.tf
# ssh key resource "tls_private_key" "ssh_key" { algorithm = "RSA" rsa_bits = 4096 }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/gcp/outputs.tf
output "cloud" { value = "gcp" } output "isaac_ip" { value = var.isaac_enabled ? module.isaac[0].public_ip : "NA" } output "isaac_vm_id" { value = var.isaac_enabled ? module.isaac[0].vm_id : "NA" } output "ssh_key" { value = tls_private_key.ssh_key.private_key_pem sensitive = true }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/gcp/ovkit/main.tf
locals { # gcloud compute images list --filter="name~'ubuntu'" # boot_image = "ubuntu-1804-bionic-v20230308" boot_image = "ubuntu-2004-focal-v20230302" # boot_image = "ubuntu-2204-jammy-v20230415" boot_disk_size = 255 os_username = "ubuntu" } resource "google_compute_instance" "default" { name = "${var.prefix}-vm" machine_type = var.instance_type enable_display = false # allows to change instance type without destriying everything allow_stopping_for_update = true scheduling { # required when gpus are used on_host_maintenance = "TERMINATE" } boot_disk { auto_delete = true initialize_params { image = local.boot_image size = local.boot_disk_size # @see https://cloud.google.com/compute/docs/disks type = "pd-ssd" } } metadata = { ssh-keys = "${local.os_username}:${var.public_key_openssh}" } labels = { deployment = var.deployment_name } guest_accelerator { type = var.gpu_type count = var.gpu_count } network_interface { network = google_compute_network.default.self_link access_config {} } }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/gcp/ovkit/variables.tf
variable "prefix" { type = string } variable "deployment_name" { type = string } variable "public_key_openssh" { type = string } variable "instance_type" { type = string } variable "gpu_count" { type = number } variable "gpu_type" { type = string } variable "ssh_port" { type = number } variable "isaac_enabled" { type = bool default = false }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/gcp/ovkit/security.tf
resource "google_compute_network" "default" { name = "${var.prefix}-network" } # all egress resource "google_compute_firewall" "egress" { name = "${var.prefix}-fwrules-egress" network = google_compute_network.default.self_link allow { protocol = "all" } direction = "EGRESS" destination_ranges = ["0.0.0.0/0"] } # ssh resource "google_compute_firewall" "ssh" { name = "${var.prefix}-fwrules-ssh" network = google_compute_network.default.self_link allow { protocol = "tcp" ports = ["22"] } source_ranges = ["0.0.0.0/0"] } # nomachine resource "google_compute_firewall" "nomachine" { name = "${var.prefix}-fwrules-nomachine" network = google_compute_network.default.self_link allow { protocol = "udp" ports = ["4000"] } allow { protocol = "tcp" ports = ["4000"] } source_ranges = ["0.0.0.0/0"] } # vnc resource "google_compute_firewall" "vnc" { name = "${var.prefix}-fwrules-vnc" network = google_compute_network.default.self_link allow { protocol = "tcp" ports = ["5900"] } source_ranges = ["0.0.0.0/0"] } # novnc resource "google_compute_firewall" "novnc" { name = "${var.prefix}-fwrules-novnc" network = google_compute_network.default.self_link allow { protocol = "tcp" ports = ["6080"] } source_ranges = ["0.0.0.0/0"] } # custom ssh port resource "google_compute_firewall" "ssh_custom" { name = "${var.prefix}-fwrules-ssh-custom" network = google_compute_network.default.self_link allow { protocol = "tcp" ports = ["${var.ssh_port}"] } source_ranges = ["0.0.0.0/0"] }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/gcp/ovkit/outputs.tf
output "public_ip" { value = google_compute_instance.default.network_interface[0].access_config[0].nat_ip } output "vm_id" { value = google_compute_instance.default.id }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/alicloud/main.tf
terraform { required_version = ">= 1.3.5" } provider "alicloud" { access_key = var.aliyun_access_key secret_key = var.aliyun_secret_key region = var.region } module "common" { source = "./common" prefix = "${var.prefix}-${var.deployment_name}-common" region = var.region } module "isaac" { source = "./ovkit" count = var.isaac_enabled ? 1 : 0 prefix = "${var.prefix}-${var.deployment_name}-isaac" vswitch_netnum = 1 ssh_port = var.ssh_port vpc = module.common.vpc key_pair = module.common.key_pair instance_type = var.isaac_instance_type resource_group = module.common.resource_group }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/alicloud/variables.tf
variable "prefix" { type = string } variable "from_image" { type = bool } variable "deployment_name" { type = string } variable "ssh_port" { type = number } variable "aliyun_access_key" { type = string } variable "aliyun_secret_key" { type = string } variable "region" { type = string } variable "isaac_instance_type" { type = string } variable "isaac_enabled" { type = bool }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/alicloud/outputs.tf
output "cloud" { value = "alicloud" } output "ssh_key" { value = module.common.ssh_key.private_key_pem sensitive = true } output "isaac_ip" { value = try(var.isaac_enabled ? module.isaac[0].public_ip : "NA", "NA") } output "isaac_vm_id" { value = try(var.isaac_enabled ? module.isaac[0].vm_id : "NA", "NA") }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/alicloud/common/main.tf
# ssh key resource "tls_private_key" "ssh_key" { algorithm = "RSA" rsa_bits = 4096 } # resource group resource "alicloud_resource_manager_resource_group" "default" { resource_group_name = "${var.prefix}-rg" display_name = "${var.prefix}-rg" } # keypair resource "alicloud_ecs_key_pair" "default" { key_pair_name = "${var.prefix}-keypair" public_key = tls_private_key.ssh_key.public_key_openssh resource_group_id = alicloud_resource_manager_resource_group.default.id } # create vpc on alicloud resource "alicloud_vpc" "default" { vpc_name = "${var.prefix}-vpc" cidr_block = var.vpc_cidr_block resource_group_id = alicloud_resource_manager_resource_group.default.id }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/alicloud/common/variables.tf
variable "prefix" { type = string } variable "region" { type = string } variable "vpc_cidr_block" { description = "CIDR block for the entire VPC. Will be split into /24 subnet for apps." default = "10.1.0.0/16" type = string }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/alicloud/common/outputs.tf
output "ssh_key" { value = tls_private_key.ssh_key } output "vpc" { value = alicloud_vpc.default } output "resource_group" { value = alicloud_resource_manager_resource_group.default } output "key_pair" { value = alicloud_ecs_key_pair.default }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/alicloud/ovkit/main.tf
# find zones where instance is available data "alicloud_zones" "instance_availability" { available_instance_type = var.instance_type } # create a subnet for the instance on alicloud # @see: https://registry.terraform.io/providers/aliyun/alicloud/latest/docs/resources/vswitch resource "alicloud_vswitch" "default" { vswitch_name = "${var.prefix}-vswitch" vpc_id = var.vpc.id cidr_block = cidrsubnet(var.vpc.cidr_block, 8, var.vswitch_netnum) zone_id = try(sort(data.alicloud_zones.instance_availability.ids)[0], "not-available") } # elastic ip # @see: https://registry.terraform.io/providers/aliyun/alicloud/latest/docs/resources/eip_address # TODO: check if isp needs special setting for China (https://registry.terraform.io/providers/aliyun/alicloud/latest/docs/resources/eip_address#isp) resource "alicloud_eip_address" "default" { address_name = "${var.prefix}-eip" resource_group_id = var.resource_group.id bandwidth = "200" internet_charge_type = "PayByTraffic" } # create instance # @see: https://registry.terraform.io/providers/aliyun/alicloud/latest/docs/resources/instance resource "alicloud_instance" "default" { instance_name = "${var.prefix}-vm" resource_group_id = var.resource_group.id host_name = "${var.prefix}-vm" instance_type = var.instance_type internet_charge_type = "PayByTraffic" stopped_mode = "StopCharging" image_id = "ubuntu_20_04_x64_20G_alibase_20230907.vhd" key_name = var.key_pair.key_pair_name vswitch_id = alicloud_vswitch.default.id security_groups = alicloud_security_group.default.*.id availability_zone = try(sort(data.alicloud_zones.instance_availability.ids)[0], "not-available") # @see: https://www.alibabacloud.com/help/en/ecs/user-guide/essds system_disk_performance_level = "PL1" system_disk_size = var.disk_size_gib system_disk_category = "cloud_auto" # by default, only root user exists in ubuntu image # create a new user, add public key, add user to sudoers user_data = base64encode(<<-EOF #!/bin/bash USERNAME="ubuntu" useradd -m -d /home/$USERNAME -s /bin/bash $USERNAME mkdir /home/$USERNAME/.ssh cat /root/.ssh/authorized_keys >> /home/$USERNAME/.ssh/authorized_keys cp /home/$USERNAME/.ssh/authorized_keys /home/$USERNAME/.ssh/authorized_keys.bak uniq /home/$USERNAME/.ssh/authorized_keys.bak > /home/$USERNAME/.ssh/authorized_keys chown -R $USERNAME:$USERNAME /home/$USERNAME echo "$USERNAME ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers EOF ) } resource "alicloud_eip_association" "default" { instance_id = alicloud_instance.default.id allocation_id = alicloud_eip_address.default.id }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/alicloud/ovkit/variables.tf
variable "prefix" { type = string } variable "instance_type" { type = string } variable "ssh_port" { type = number } variable "vswitch_netnum" { description = "The number of the subnet to use for the app vswitch. 1-255." type = number } variable "disk_size_gib" { type = number default = 256 } variable "vpc" { } variable "resource_group" { } variable "key_pair" { }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/alicloud/ovkit/security.tf
resource "alicloud_security_group" "default" { name = "${var.prefix}-sg" vpc_id = var.vpc.id } # security rule for ssh resource "alicloud_security_group_rule" "allow_ssh" { priority = 1 security_group_id = alicloud_security_group.default.id type = "ingress" ip_protocol = "tcp" nic_type = "intranet" policy = "accept" port_range = "22/22" cidr_ip = "0.0.0.0/0" } # security rule for novnc resource "alicloud_security_group_rule" "allow_novnc" { priority = 2 security_group_id = alicloud_security_group.default.id type = "ingress" ip_protocol = "tcp" nic_type = "intranet" policy = "accept" port_range = "6080/6080" cidr_ip = "0.0.0.0/0" } # security rule for ping resource "alicloud_security_group_rule" "allow_ping" { priority = 3 security_group_id = alicloud_security_group.default.id type = "ingress" ip_protocol = "icmp" nic_type = "intranet" policy = "accept" port_range = "-1/-1" cidr_ip = "0.0.0.0/0" } # security rule for nomachine resource "alicloud_security_group_rule" "allow_nomachine" { priority = 4 security_group_id = alicloud_security_group.default.id type = "ingress" ip_protocol = "tcp" nic_type = "intranet" policy = "accept" port_range = "4000/4000" cidr_ip = "0.0.0.0/0" } # custom ssh port resource "alicloud_security_group_rule" "custom_ssh" { priority = 5 count = var.ssh_port != 22 ? 1 : 0 security_group_id = alicloud_security_group.default.id type = "ingress" ip_protocol = "tcp" nic_type = "intranet" policy = "accept" port_range = "${var.ssh_port}/${var.ssh_port}" cidr_ip = "0.0.0.0/0" }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/alicloud/ovkit/outputs.tf
output "public_ip" { value = alicloud_eip_address.default.ip_address } output "vm_id" { value = alicloud_instance.default.id }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/azure/main.tf
# Configure the Azure provider terraform { required_version = ">= 1.3.5" required_providers { azurerm = { source = "hashicorp/azurerm" version = "~> 2.99" } } } provider "azurerm" { features { resource_group { prevent_deletion_if_contains_resources = true } virtual_machine { delete_os_disk_on_deletion = true graceful_shutdown = false skip_shutdown_and_force_delete = false } } } module "common" { source = "./common" prefix = "${var.prefix}.${var.deployment_name}" region = var.region resource_group_name = var.resource_group_name } module "isaac" { source = "./isaac" count = var.isaac_enabled ? 1 : 0 prefix = "${var.prefix}.${var.deployment_name}.isaac" rg = module.common.rg subnet = module.common.subnet ssh_key = module.common.ssh_key vm_type = var.isaac_instance_type from_image = var.from_image ssh_port = var.ssh_port }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/azure/variables.tf
variable "prefix" { type = string } variable "deployment_name" { default = "test0" type = string } variable "region" { default = "westus3" } variable "resource_group_name" { type = string } variable "isaac_enabled" { default = true } variable "isaac_instance_type" { type = string } variable "from_image" { default = false type = bool } variable "ssh_port" { type = number }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/azure/outputs.tf
output "isaac_ip" { value = var.isaac_enabled ? module.isaac[0].public_ip : "NA" } output "isaac_vm_id" { value = var.isaac_enabled ? module.isaac[0].vm_id : "NA" } # we cant have aws ami on azure, who could think output "ovami_ip" { value = "NA" } output "ssh_key" { value = module.common.ssh_key.private_key_pem sensitive = true } output "cloud" { value = "azure" }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/azure/isaac/main.tf
resource "azurerm_public_ip" "public_ip" { name = "${var.prefix}.public_ip" location = var.rg.location resource_group_name = var.rg.name allocation_method = "Static" } resource "azurerm_network_interface" "nic" { name = "${var.prefix}.nic" location = var.rg.location resource_group_name = var.rg.name ip_configuration { name = "${var.prefix}.nic_config" subnet_id = var.subnet.id private_ip_address_allocation = "Dynamic" public_ip_address_id = azurerm_public_ip.public_ip.id } } resource "azurerm_network_interface_security_group_association" "nic_sg_association" { network_interface_id = azurerm_network_interface.nic.id network_security_group_id = azurerm_network_security_group.sg.id } resource "azurerm_linux_virtual_machine" "vm_from_scratch" { name = "${var.prefix}.vm" location = var.rg.location resource_group_name = var.rg.name network_interface_ids = [azurerm_network_interface.nic.id] size = var.vm_type # no docs, but https://github.com/hashicorp/terraform-provider-azurerm/issues/160#issuecomment-338666563 os_disk { name = "${var.prefix}.os_disk" caching = "ReadWrite" storage_account_type = "Premium_LRS" # Standard_LRS, StandardSSD_LRS, Premium_LRS disk_size_gb = 256 } # list all: # az vm image list --all --publisher Canonical --offer ubuntu-server --sku 20_04-lts | jq -c '.[] | select(.sku=="20_04-lts")' source_image_reference { publisher = "Canonical" offer = "0001-com-ubuntu-server-focal" sku = "20_04-lts-gen2" version = "20.04.202301100" } computer_name = "isaac" admin_username = "ubuntu" disable_password_authentication = true admin_ssh_key { username = "ubuntu" public_key = var.ssh_key.public_key_openssh } count = var.from_image ? 0 : 1 } resource "azurerm_linux_virtual_machine" "vm_from_image" { name = "${var.prefix}.vm" location = var.rg.location resource_group_name = var.rg.name network_interface_ids = [azurerm_network_interface.nic.id] size = var.vm_type # no docs, but https://github.com/hashicorp/terraform-provider-azurerm/issues/160#issuecomment-338666563 os_disk { name = "${var.prefix}.os_disk" caching = "ReadWrite" storage_account_type = "Premium_LRS" # Standard_LRS, StandardSSD_LRS, Premium_LRS disk_size_gb = 256 } # TODO: use public image # TODO: update image name source_image_id = "/subscriptions/4ca485f9-4cdf-4749-9d14-320dd780fc1c/resourceGroups/isa.PACKER/providers/Microsoft.Compute/images/isa.isaac_image" computer_name = "isaac" admin_username = "ubuntu" disable_password_authentication = true admin_ssh_key { username = "ubuntu" public_key = var.ssh_key.public_key_openssh } count = var.from_image ? 1 : 0 }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/azure/isaac/variables.tf
variable "prefix" { default = null } variable "rg" { default = null } variable "subnet" { default = null } variable "ssh_key" { default = null } variable "vm_type" { type = string } variable "from_image" { default = false type = bool } variable "ssh_port" { type = number }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/azure/isaac/security.tf
resource "azurerm_network_security_group" "sg" { name = "${var.prefix}.sg" location = var.rg.location resource_group_name = var.rg.name security_rule { name = "SSH" priority = 1001 direction = "Inbound" access = "Allow" protocol = "Tcp" source_port_range = "*" destination_port_range = "22" source_address_prefix = "*" destination_address_prefix = "*" } security_rule { name = "NoMachine" priority = 102 direction = "Inbound" access = "Allow" protocol = "*" source_port_range = "*" destination_port_ranges = ["4000"] source_address_prefix = "*" destination_address_prefix = "*" } security_rule { name = "VNC" priority = 103 direction = "Inbound" access = "Allow" protocol = "TCP" source_port_range = "*" destination_port_ranges = ["5900"] source_address_prefix = "*" destination_address_prefix = "*" } security_rule { name = "noVNC" priority = 106 direction = "Inbound" access = "Allow" protocol = "TCP" source_port_range = "*" destination_port_ranges = ["6080"] source_address_prefix = "*" destination_address_prefix = "*" } } # security rule for custom ssh port resource "azurerm_network_security_rule" "custom_ssh" { name = "Custom_SSH" priority = 104 direction = "Inbound" access = "Allow" protocol = "Tcp" source_port_range = "*" destination_port_range = var.ssh_port source_address_prefix = "*" destination_address_prefix = "*" network_security_group_name = azurerm_network_security_group.sg.name resource_group_name = var.rg.name count = var.ssh_port != 22 ? 1 : 0 }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/azure/isaac/outputs.tf
output "public_ip" { value = try(var.from_image ? azurerm_linux_virtual_machine.vm_from_image[0].public_ip_address : azurerm_linux_virtual_machine.vm_from_scratch[0].public_ip_address, "NA") } output "vm_id" { value = try(var.from_image ? azurerm_linux_virtual_machine.vm_from_image[0].id : azurerm_linux_virtual_machine.vm_from_scratch[0].id, "NA") }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/azure/common/main.tf
# resource group resource "azurerm_resource_group" "isa_rg" { name = var.resource_group_name location = var.region } # virtual network resource "azurerm_virtual_network" "isa_network" { name = "${var.prefix}.vnet" address_space = ["10.0.0.0/16"] location = azurerm_resource_group.isa_rg.location resource_group_name = azurerm_resource_group.isa_rg.name } # subnet resource "azurerm_subnet" "isa_subnet" { name = "${var.prefix}.subnet" resource_group_name = azurerm_resource_group.isa_rg.name virtual_network_name = azurerm_virtual_network.isa_network.name address_prefixes = ["10.0.1.0/24"] } # ssh key resource "tls_private_key" "ssh_key" { algorithm = "RSA" rsa_bits = 4096 }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/azure/common/variables.tf
variable "prefix" { default = null } variable "region" { default = null } variable "resource_group_name" { default = null }
NVIDIA-Omniverse/IsaacSim-Automator/src/terraform/azure/common/outputs.tf
output "rg" { value = azurerm_resource_group.isa_rg } output "vnet" { value = azurerm_virtual_network.isa_network } output "subnet" { value = azurerm_subnet.isa_subnet } output "ssh_key" { value = tls_private_key.ssh_key }
NVIDIA-Omniverse/synthetic-data-examples/README.md
# Synthetic Data Examples This public repository is for examples of the generation and/or use of synthetic data, primarily using tools like [NVIDIA Omniverse](https://www.nvidia.com/en-us/omniverse/), [Omniverse Replicator](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_replicator.html), [NVIDIA Tao](https://developer.nvidia.com/tao-toolkit), and [NVIDIA NGC](https://www.nvidia.com/en-us/gpu-cloud/). ## Synthetic Data Blogs & Repositories * [Blog - How to Train Autonomous Mobile Robots to Detect Warehouse Pallet Jacks](https://developer.nvidia.com/blog/how-to-train-autonomous-mobile-robots-to-detect-warehouse-pallet-jacks-using-synthetic-data/) [GitHub](https://github.com/NVIDIA-AI-IOT/synthetic_data_generation_training_workflow) * [Blog - Developing a Pallet Detection Model Using OpenUSD and Synthetic Data](https://developer.nvidia.com/blog/developing-a-pallet-detection-model-using-openusd-and-synthetic-data/) [GitHub](https://github.com/NVIDIA-AI-IOT/sdg_pallet_model)
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/README.md
# Omniverse Replicator Examples Code here requires the installation of[NVIDIA Omniverse](https://www.nvidia.com/en-us/omniverse/) and [Omniverse Replicator](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_replicator.html).
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/replicator_trigger_intervals.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. # SPDX-License-Identifier: BSD-3-Clause # # Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import omni.replicator.core as rep with rep.new_layer(): camera = rep.create.camera(position=(0, 500, 1000), look_at=(0, 0, 0)) # Create simple shapes to manipulate plane = rep.create.plane( semantics=[("class", "plane")], position=(0, -100, 0), scale=(100, 1, 100) ) spheres = rep.create.sphere( semantics=[("class", "sphere")], position=(0, 0, 100), count=6 ) # Modify the position every 5 frames with rep.trigger.on_frame(num_frames=10, interval=5): with spheres: rep.modify.pose( position=rep.distribution.uniform((-300, 0, -300), (300, 0, 300)), scale=rep.distribution.uniform(0.1, 2), ) # Modify color every frame for 50 frames with rep.trigger.on_frame(num_frames=50): with spheres: rep.randomizer.color( colors=rep.distribution.normal((0.1, 0.1, 0.1), (1.0, 1.0, 1.0)) ) render_product = rep.create.render_product(camera, (512, 512)) writer = rep.WriterRegistry.get("BasicWriter") writer.initialize( output_dir="trigger_intervals", rgb=True, ) writer.attach([render_product])
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/replicator_light_modification.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. # SPDX-License-Identifier: BSD-3-Clause # # Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ This snippet shows how to modify attributes on prims that Replicator may not have a direct functional mapping for. """ import omni.replicator.core as rep with rep.new_layer(): camera = rep.create.camera(position=(0, 500, 1000), look_at=(0, 0, 0)) # Create simple shapes to manipulate plane = rep.create.plane( semantics=[("class", "plane")], position=(0, -100, 0), scale=(100, 1, 100) ) cubes = rep.create.cube( semantics=[("class", "cube")], position=rep.distribution.uniform((-300, 0, -300), (300, 0, 300)), count=6, ) spheres = rep.create.sphere( semantics=[("class", "sphere")], position=rep.distribution.uniform((-300, 0, -300), (300, 0, 300)), count=6, ) lights = rep.create.light( light_type="Sphere", intensity=rep.distribution.normal(500, 35000), position=rep.distribution.uniform((-300, 300, -300), (300, 1000, 300)), scale=rep.distribution.uniform(50, 100), count=3, ) with rep.trigger.on_frame(num_frames=10): with lights: rep.modify.pose( position=rep.distribution.uniform((-300, 300, -300), (300, 1000, 300)) ) rep.modify.attribute("intensity", rep.distribution.uniform(1.0, 50000.0)) rep.modify.attribute( "color", rep.distribution.normal((0.2, 0.2, 0.2), (1.0, 1.0, 1.0)) )
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/replicator_multiple_semantic_classes.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. # SPDX-License-Identifier: BSD-3-Clause # # Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import omni.replicator.core as rep with rep.new_layer(): sphere = rep.create.sphere(semantics=[("class", "sphere")], position=(0, 100, 100)) cube = rep.create.cube(semantics=[("class2", "cube")], position=(200, 200, 100)) plane = rep.create.plane(semantics=[("class3", "plane")], scale=10) def get_shapes(): shapes = rep.get.prims(semantics=[("class", "cube"), ("class", "sphere")]) with shapes: rep.modify.pose( position=rep.distribution.uniform((-500, 50, -500), (500, 50, 500)), rotation=rep.distribution.uniform((0, -180, 0), (0, 180, 0)), scale=rep.distribution.normal(1, 0.5), ) return shapes.node with rep.trigger.on_frame(num_frames=2): rep.randomizer.register(get_shapes) # Setup Camera camera = rep.create.camera(position=(500, 500, 500), look_at=(0, 0, 0)) render_product = rep.create.render_product(camera, (512, 512)) writer = rep.WriterRegistry.get("BasicWriter") writer.initialize( output_dir="semantics_classes", rgb=True, semantic_segmentation=True, colorize_semantic_segmentation=True, semantic_types=["class", "class2", "class3"], ) writer.attach([render_product]) rep.orchestrator.run()
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/replicator_scatter_multi_trigger.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # """ This snippet shows how to setup multiple independent triggers that happen at different intervals in the simulation. """ import omni.graph.core as og import omni.replicator.core as rep # A light to see distance_light = rep.create.light(rotation=(-45, 0, 0), light_type="distant") # Create a plane to sample on plane_samp = rep.create.plane(scale=4, rotation=(20, 0, 0)) # Create a larger sphere to sample on the surface of sphere_samp = rep.create.sphere(scale=2.4, position=(0, 100, -180)) # Create a larger cylinder we do not want to collide with cylinder = rep.create.cylinder(semantics=[("class", "cylinder")], scale=(2, 1, 2)) def randomize_spheres(): # create small spheres to sample inside the plane spheres = rep.create.sphere(scale=0.4, count=60) # scatter small spheres with spheres: rep.randomizer.scatter_2d( surface_prims=[plane_samp, sphere_samp], no_coll_prims=[cylinder], check_for_collisions=True, ) # Add color to small spheres rep.randomizer.color( colors=rep.distribution.uniform((0.2, 0.2, 0.2), (1, 1, 1)) ) return spheres.node rep.randomizer.register(randomize_spheres) # Trigger will execute 5 times, every-other-frame (interval=2) with rep.trigger.on_frame(num_frames=5, interval=2): rep.randomizer.randomize_spheres() # Trigger will execute 10 times, once every frame with rep.trigger.on_frame(num_frames=10): with cylinder: rep.modify.visibility(rep.distribution.sequence([True, False])) og.Controller.evaluate_sync() # Only for snippet demonstration preview, not needed for production rep.orchestrator.preview() # Only for snippet demonstration preview, not needed for production rp = rep.create.render_product("/OmniverseKit_Persp", (1024, 768)) # Initialize and attach writer writer = rep.WriterRegistry.get("BasicWriter") writer.initialize(output_dir="scatter_example", rgb=True) writer.attach([rp]) rep.orchestrator.run()
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/replicator_writer_segmentation_colors.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. # SPDX-License-Identifier: BSD-3-Clause # # Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ A snippet showing to how create a custom writer to output specific colors in the semantic annotator output image. """ import omni.replicator.core as rep from omni.replicator.core import Writer, BackendDispatch, WriterRegistry class MyWriter(Writer): def __init__(self, output_dir: str): self._frame_id = 0 self.backend = BackendDispatch({"paths": {"out_dir": output_dir}}) self.annotators = ["rgb", "semantic_segmentation"] # Dictionary mapping of label to RGBA color self.CUSTOM_LABELS = { "unlabelled": (0, 0, 0, 0), "sphere": (128, 64, 128, 255), "cube": (244, 35, 232, 255), "plane": (102, 102, 156, 255), } def write(self, data): render_products = [k for k in data.keys() if k.startswith("rp_")] self._write_rgb(data, "rgb") self._write_segmentation(data, "semantic_segmentation") self._frame_id += 1 def _write_rgb(self, data, annotator: str): # Save the rgb data under the correct path rgb_file_path = f"rgb_{self._frame_id}.png" self.backend.write_image(rgb_file_path, data[annotator]) def _write_segmentation(self, data, annotator: str): seg_filepath = f"seg_{self._frame_id}.png" semantic_seg_data_colorized = rep.tools.colorize_segmentation( data[annotator]["data"], data[annotator]["info"]["idToLabels"], mapping=self.CUSTOM_LABELS, ) self.backend.write_image(seg_filepath, semantic_seg_data_colorized) def on_final_frame(self): self.backend.sync_pending_paths() # Register new writer WriterRegistry.register(MyWriter) # Create a new layer for our work to be performed in. # This is a good habit to develop for later when working on existing Usd scenes with rep.new_layer(): light = rep.create.light(light_type="dome") # Create a simple camera with a position and a point to look at camera = rep.create.camera(position=(0, 500, 1000), look_at=(0, 0, 0)) # Create some simple shapes to manipulate plane = rep.create.plane( semantics=[("class", "plane")], position=(0, -100, 0), scale=(100, 1, 100) ) torus = rep.create.torus(position=(200, 0, 100)) # Torus will be unlabeled sphere = rep.create.sphere(semantics=[("class", "sphere")], position=(0, 0, 100)) cube = rep.create.cube(semantics=[("class", "cube")], position=(-200, 0, 100)) # Randomize position and scale of each object on each frame with rep.trigger.on_frame(num_frames=10): # Creating a group so that our modify.pose operation works on all the shapes at once with rep.create.group([torus, sphere, cube]): rep.modify.pose( position=rep.distribution.uniform((-300, 0, -300), (300, 0, 300)), scale=rep.distribution.uniform(0.1, 2), ) # Initialize render product and attach a writer render_product = rep.create.render_product(camera, (1024, 1024)) writer = rep.WriterRegistry.get("MyWriter") writer.initialize(output_dir="myWriter_output") writer.attach([render_product]) rep.orchestrator.run() # Run the simulation
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/replicator_remove_semantics.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. # SPDX-License-Identifier: BSD-3-Clause # # Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import omni.graph.core as og import omni.replicator.core as rep from omni.usd._impl.utils import get_prim_at_path from pxr import Semantics from semantics.schema.editor import remove_prim_semantics # Setup simple scene with rep.new_layer(): # Simple scene setup camera = rep.create.camera(position=(0, 500, 1000), look_at=(0, 0, 0)) # Create simple shapes to manipulate plane = rep.create.plane( semantics=[("class", "plane")], position=(0, -100, 0), scale=(100, 1, 100) ) cubes = rep.create.cube( semantics=[("class", "cube")], position=rep.distribution.uniform((-300, 0, -300), (300, 0, 300)), count=6, ) spheres = rep.create.sphere( semantics=[("class", "sphere")], position=rep.distribution.uniform((-300, 0, -300), (300, 0, 300)), count=6, ) # Get prims to remove semantics on - Execute this first by itself my_spheres = rep.get.prims(semantics=[("class", "sphere")]) og.Controller.evaluate_sync() # Trigger an OmniGraph evaluation of the graph to set the values get_targets = rep.utils.get_node_targets(my_spheres.node, "outputs_prims") print(get_targets) # [Sdf.Path('/Replicator/Sphere_Xform'), Sdf.Path('/Replicator/Sphere_Xform_01'), Sdf.Path('/Replicator/Sphere_Xform_02'), Sdf.Path('/Replicator/Sphere_Xform_03'), Sdf.Path('/Replicator/Sphere_Xform_04'), Sdf.Path('/Replicator/Sphere_Xform_05')] # Loop through each prim_path and remove all semantic data for prim_path in get_targets: prim = get_prim_at_path(prim_path) # print(prim.HasAPI(Semantics.SemanticsAPI)) result = remove_prim_semantics(prim) # To remove all semantics # result = remove_prim_semantics(prim, label_type='class') # To remove only 'class' semantics print(result)
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/replcator_clear_layer.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. # SPDX-License-Identifier: BSD-3-Clause # # Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import omni.usd stage = omni.usd.get_context().get_stage() for layer in stage.GetLayerStack(): if layer.GetDisplayName() == "test": # del layer layer.Clear()
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/replicator_time_intervals.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. # SPDX-License-Identifier: BSD-3-Clause # # Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import omni.replicator.core as rep with rep.new_layer(): camera = rep.create.camera(position=(0, 500, 1000), look_at=(0, 0, 0)) # Create simple shapes to manipulate plane = rep.create.plane( semantics=[("class", "plane")], position=(0, -100, 0), scale=(100, 1, 100) ) spheres = rep.create.sphere( semantics=[("class", "sphere")], position=(0, 0, 100), count=6 ) with rep.trigger.on_time(num=10, interval=5): with spheres: rep.modify.pose( position=rep.distribution.uniform((-300, 0, -300), (300, 0, 300)), scale=rep.distribution.uniform(0.1, 2), ) with rep.trigger.on_time(num=50): with spheres: rep.randomizer.color( colors=rep.distribution.normal((0.1, 0.1, 0.1), (1.0, 1.0, 1.0)) ) render_product = rep.create.render_product(camera, (512, 512)) writer = rep.WriterRegistry.get("BasicWriter") writer.initialize( output_dir="time_intervals", rgb=True, ) writer.attach([render_product])
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/replicator_annotator_segmentation.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. # SPDX-License-Identifier: BSD-3-Clause # # Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ This is an example of how to view annotator data if needed. """ import asyncio import omni.replicator.core as rep import omni.syntheticdata as sd async def test_semantics(): cone = rep.create.cone(semantics=[("prim", "cone")], position=(100, 0, 0)) sphere = rep.create.sphere(semantics=[("prim", "sphere")], position=(-100, 0, 0)) invalid_type = rep.create.cube(semantics=[("shape", "boxy")], position=(0, 100, 0)) # Setup semantic filter # sd.SyntheticData.Get().set_instance_mapping_semantic_filter("prim:*") cam = rep.create.camera(position=(500, 500, 500), look_at=(0, 0, 0)) rp = rep.create.render_product(cam, (1024, 512)) segmentation = rep.AnnotatorRegistry.get_annotator("semantic_segmentation") segmentation.attach(rp) # step_async() tells Omniverse to update, otherwise the annoation buffer could be empty await rep.orchestrator.step_async() data = segmentation.get_data() print(data) # Example Output: # { # "data": array( # [ # [0, 0, 0, ..., 0, 0, 0], # [0, 0, 0, ..., 0, 0, 0], # [0, 0, 0, ..., 0, 0, 0], # ..., # [0, 0, 0, ..., 0, 0, 0], # [0, 0, 0, ..., 0, 0, 0], # [0, 0, 0, ..., 0, 0, 0], # ], # dtype=uint32, # ), # "info": { # "_uniqueInstanceIDs": array([1, 1, 1], dtype=uint8), # "idToLabels": { # "0": {"class": "BACKGROUND"}, # "2": {"prim": "cone"}, # "3": {"prim": "sphere"}, # "4": {"shape": "boxy"}, # }, # }, # } asyncio.ensure_future(test_semantics())
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/replicator_multi_object_visibility_toggle.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. # SPDX-License-Identifier: BSD-3-Clause # # Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """This will create a group from a list of objects and 1. Render all the objects together 2. Toggle sole visiblity for each object & render 3. Randomize pose for all objects, repeat This can be useful for training on object occlusions. """ import omni.replicator.core as rep NUM_POSE_RANDOMIZATIONS = 10 # Make a list-of-lists of True/False for each object # In this example of 3 objects: # [[True, True, True] # [True, False, False] # [False, True, False] # [False, False, True]] def make_visibility_lists(num_objects): visib = [] # Make an all-visible first pass visib.append(tuple([True for x in range(num_objects)])) # List to toggle one object visible at a time for x in range(num_objects): sub_vis = [] for i in range(num_objects): if x == i: sub_vis.append(True) else: sub_vis.append(False) visib.append(tuple(sub_vis)) return visib with rep.new_layer(): # Setup camera and simple light camera = rep.create.camera(position=(0, 500, 1000), look_at=(0, 0, 0)) light = rep.create.light(rotation=(-45, 45, 0)) # Create simple shapes to manipulate plane = rep.create.plane( semantics=[("class", "plane")], position=(0, -100, 0), scale=(100, 1, 100) ) torus = rep.create.torus(semantics=[("class", "torus")], position=(200, 0, 100)) sphere = rep.create.sphere(semantics=[("class", "sphere")], position=(0, 0, 100)) cube = rep.create.cube(semantics=[("class", "cube")], position=(-200, 0, 100)) # Create a group of the objects we will be manipulating # Leaving-out camera, light, and plane from visibility toggling and pose randomization object_group = rep.create.group([torus, sphere, cube]) # Get the number of objects to toggle, can work with any number of objects num_objects_to_toggle = len(object_group.get_output_prims()["prims"]) # Create our lists-of-lists for visibility visibility_sequence = make_visibility_lists(num_objects_to_toggle) # Trigger to toggle visibility one at a time with rep.trigger.on_frame( max_execs=(num_objects_to_toggle + 1) * NUM_POSE_RANDOMIZATIONS ): with object_group: rep.modify.visibility(rep.distribution.sequence(visibility_sequence)) # Trigger to randomize position and scale, interval set to number of objects +1(1 extra for the "all visible" frame) with rep.trigger.on_frame( max_execs=NUM_POSE_RANDOMIZATIONS, interval=num_objects_to_toggle + 1 ): with object_group: rep.modify.pose( position=rep.distribution.uniform((-300, 0, -300), (300, 0, 300)), scale=rep.distribution.uniform(0.1, 2), ) # Initialize render product and attach writer render_product = rep.create.render_product(camera, (512, 512)) writer = rep.WriterRegistry.get("BasicWriter") writer.initialize( output_dir="toggle_multi_visibility", rgb=True, semantic_segmentation=True, ) writer.attach([render_product]) rep.orchestrator.run()
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/replicator_filter_semantics.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. # SPDX-License-Identifier: BSD-3-Clause # # Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ This snippet shows how to use semantic filtering to remove labels or entire prims with specific semantic labels from being output to the semantic annotator https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_replicator/semantics_schema_editor.html """ import omni.replicator.core as rep from omni.syntheticdata import SyntheticData with rep.new_layer(): camera = rep.create.camera(position=(0, 500, 1000), look_at=(0, 0, 0)) # Create simple shapes to manipulate plane = rep.create.plane( semantics=[("class", "plane")], position=(0, -100, 0), scale=(100, 1, 100) ) cubes = rep.create.cube( semantics=[("class", "cube")], position=rep.distribution.uniform((-300, 0, -300), (300, 0, 300)), count=6, ) spheres = rep.create.sphere( semantics=[("class", "sphere")], position=rep.distribution.uniform((-300, 0, -300), (300, 0, 300)), count=6, ) # 10 Frames of randomizations, randomizing colors for spheres and cubes independent of each other with rep.trigger.on_frame(num_frames=10): with cubes: rep.randomizer.color( colors=rep.distribution.normal((0.2, 0.2, 0.2), (1.0, 1.0, 1.0)) ) with spheres: rep.randomizer.color( colors=rep.distribution.normal((0.2, 0.2, 0.2), (1.0, 1.0, 1.0)) ) render_product = rep.create.render_product(camera, (512, 512)) writer = rep.WriterRegistry.get("BasicWriter") writer.initialize( output_dir="filter_semantics", rgb=True, semantic_segmentation=True, colorize_semantic_segmentation=True, ) # Filter class:sphere objects (_after_ BasicWriter is initialized) # https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_replicator/semantics_schema_editor.html SyntheticData.Get().set_instance_mapping_semantic_filter("class:!sphere") writer.attach([render_product]) rep.orchestrator.run()
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/scattering/scatter2D_multi_surface.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # import omni.graph.core as og import omni.replicator.core as rep # A light to see distance_light = rep.create.light(rotation=(-45, 0, 0), light_type="distant") # Create a plane to sample on plane_samp = rep.create.plane(scale=4, rotation=(20, 0, 0)) # Create a larger sphere to sample on the surface of sphere_samp = rep.create.sphere(scale=2.4, position=(0, 100, -180)) def randomize_spheres(): # create small spheres to sample inside the plane spheres = rep.create.sphere(scale=0.4, count=40) # scatter small spheres with spheres: rep.randomizer.scatter_2d( surface_prims=[plane_samp, sphere_samp], check_for_collisions=True ) # Add color to small spheres rep.randomizer.color( colors=rep.distribution.uniform((0.2, 0.2, 0.2), (1, 1, 1)) ) return spheres.node rep.randomizer.register(randomize_spheres) with rep.trigger.on_frame(num_frames=10): rep.randomizer.randomize_spheres() og.Controller.evaluate_sync() rep.orchestrator.preview()
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/scattering/scatter2D_basic.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # import omni.graph.core as og import omni.replicator.core as rep # create a plane to sample on plane_samp = rep.create.plane(scale=4, rotation=(20, 0, 0)) def randomize_spheres(): # create small spheres to sample inside the plane spheres = rep.create.sphere(scale=0.4, count=30) # randomize with spheres: rep.randomizer.scatter_2d(plane_samp, check_for_collisions=True) # Add color to small spheres rep.randomizer.color( colors=rep.distribution.uniform((0.2, 0.2, 0.2), (1, 1, 1)) ) return spheres.node rep.randomizer.register(randomize_spheres) with rep.trigger.on_frame(num_frames=10): rep.randomizer.randomize_spheres() og.Controller.evaluate_sync() rep.orchestrator.preview()
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/scattering/scatter2D_avoid_objects.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # import omni.graph.core as og import omni.replicator.core as rep # A light to see distance_light = rep.create.light(rotation=(-45, 0, 0), light_type="distant") # Create a plane to sample on plane_samp = rep.create.plane(scale=4, rotation=(20, 0, 0)) # Create a larger sphere to sample on the surface of sphere_samp = rep.create.sphere(scale=2.4, position=(0, 100, -180)) # Create a larger cylinder we do not want to collide with cylinder = rep.create.cylinder(semantics=[("class", "cylinder")], scale=(2, 1, 2)) def randomize_spheres(): # create small spheres to sample inside the plane spheres = rep.create.sphere(scale=0.4, count=40) # scatter small spheres with spheres: rep.randomizer.scatter_2d( surface_prims=[plane_samp, sphere_samp], no_coll_prims=[cylinder], check_for_collisions=True, ) # Add color to small spheres rep.randomizer.color( colors=rep.distribution.uniform((0.2, 0.2, 0.2), (1, 1, 1)) ) return spheres.node rep.randomizer.register(randomize_spheres) with rep.trigger.on_frame(num_frames=10): rep.randomizer.randomize_spheres() og.Controller.evaluate_sync() rep.orchestrator.preview()