---
# NOTE(mgoddard): After OVN DB leader restarts there is a period before a new
# leader has been elected where the old leader is returned in the cluster
# status. This can result in a failure to apply the connection settings if a
# different leader is elected.  Wait for a few seconds for the leader election
# to complete.
- name: Wait for leader election
  pause:
    seconds: "{{ ovn_leader_election_pause }}"
  when: ovn_nb_db_cluster_exists | default(false) or ovn_sb_db_cluster_exists | default(false)

- name: Get OVN_Northbound cluster leader
  become: true
  command: "{{ kolla_container_engine }} exec ovn_nb_db ovs-appctl -t /var/run/ovn/ovnnb_db.ctl cluster/status OVN_Northbound"
  changed_when: False
  register: ovn_nb_cluster_status

- name: Configure OVN NB connection settings
  vars:
    search_string: "Role: leader"
  become: true
  command: "{{ kolla_container_engine }} exec ovn_nb_db ovn-nbctl --inactivity-probe={{ ovn_nb_db_inactivity_probe }} set-connection ptcp:{{ ovn_nb_db_port }}:0.0.0.0"
  when: ovn_nb_cluster_status is search(search_string)

- name: Get OVN_Southbound cluster leader
  become: true
  command: "{{ kolla_container_engine }} exec ovn_sb_db ovs-appctl -t /var/run/ovn/ovnsb_db.ctl cluster/status OVN_Southbound"
  changed_when: False
  register: ovn_sb_cluster_status

- name: Configure OVN SB connection settings
  vars:
    search_string: "Role: leader"
  become: true
  command: "{{ kolla_container_engine }} exec ovn_sb_db ovn-sbctl --inactivity-probe={{ ovn_sb_db_inactivity_probe }} set-connection ptcp:{{ ovn_sb_db_port }}:0.0.0.0"
  when: ovn_sb_cluster_status is search(search_string)

- name: Wait for ovn-nb-db
  wait_for:
    host: "{{ api_interface_address }}"
    port: "{{ ovn_nb_db_port }}"
    connect_timeout: 1
    timeout: 60
  register: check_ovn_nb_db_port
  until: check_ovn_nb_db_port is success
  retries: 10
  delay: 6

- name: Wait for ovn-sb-db
  wait_for:
    host: "{{ api_interface_address }}"
    port: "{{ ovn_sb_db_port }}"
    connect_timeout: 1
    timeout: 60
  register: check_ovn_sb_db_port
  until: check_ovn_sb_db_port is success
  retries: 10
  delay: 6

- name: Wait for ovn-sb-db-relay
  vars:
    ovn_sb_db_relay_group_id: "{{ item }}"
    ovn_sb_db_relay_port: "{{ ovn_sb_db_relay_port_prefix ~ ovn_sb_db_relay_group_id }}"
  wait_for:
    host: "{{ api_interface_address }}"
    port: "{{ ovn_sb_db_relay_port }}"
    connect_timeout: 1
    timeout: 60
  register: check_ovn_sb_db_relay_port
  until: check_ovn_sb_db_relay_port is success
  retries: 10
  delay: 6
  when:
    - enable_ovn_sb_db_relay | bool
  loop: "{{ range(1, (ovn_sb_db_relay_count | int) +1) }}"
