Edits history of script submission #24009 for ' Apply config (cisco_iosxe)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    type Change = { path: string; current: any; intended: any }
    
    // Match a member by its full name, or by its local name when one side carries
    // a module prefix and the other doesn't (RFC 7951 qualifies only the top level
    // and module changes).
    function lookup(obj: { [key: string]: any }, key: string) {
      if (key in obj) return obj[key]
      const local = key.split(":").pop()
      const match = Object.keys(obj).find((k) => k.split(":").pop() === local)
      return match === undefined ? undefined : obj[match]
    }
    
    // RFC 7951 encodes 64-bit integers and decimals as strings, so "1500" and 1500
    // are the same value.
    function scalarEqual(a: any, b: any) {
      return a === b || (a != null && b != null && String(a) === String(b))
    }
    
    // Collects every place where `intended` is not already present in `current`.
    // Objects compare member by member; a list entry is satisfied when some current
    // entry contains all of its members. Members of `current` that `intended` does
    // not mention are ignored, as a PATCH merge leaves them untouched.
    function diff(intended: any, current: any, at: string, out: Change[]) {
      if (Array.isArray(intended)) {
        const entries = Array.isArray(current) ? current : []
        intended.forEach((item, i) => {
          if (!entries.some((entry) => diff(item, entry, "", []).length === 0)) {
            out.push({ path: `${at}[${i}]`, current: null, intended: item })
          }
        })
      } else if (intended !== null && typeof intended === "object") {
        // A GET on a list entry (interface/Loopback=1) returns a one-entry array.
        if (Array.isArray(current) && current.length === 1) {
          current = current[0]
        }
        if (
          current === null ||
          typeof current !== "object" ||
          Array.isArray(current)
        ) {
          out.push({ path: at || "/", current: current ?? null, intended })
        } else {
          for (const [key, value] of Object.entries(intended)) {
            diff(value, lookup(current, key), `${at}/${key}`, out)
          }
        }
      } else if (!scalarEqual(intended, current)) {
        out.push({ path: at || "/", current: current ?? null, intended })
      }
      return out
    }
    
    /**
     * Apply config
     * Declaratively apply configuration at a RESTCONF data path: read the current config there, diff it against the intended JSON, and merge (PATCH) only when they differ. intended is the RFC 7951 body wrapped in the target node, as a GET of path returns it, e.g. {"Cisco-IOS-XE-native:Loopback": {"name": 100, "description": "x"}} for path Cisco-IOS-XE-native:native/interface/Loopback=100. With dry_run (the default) nothing is changed and the diff is returned.
     */
    export async function main(
      auth: RT.CiscoIosxe,
      path: string,
      intended: { [key: string]: any },
      dry_run: boolean = true
    ) {
      const url = new URL(
        `${auth.base_url.replace(/\/+$/, "")}/restconf/data/${path.replace(/^\/+/, "")}`
      )
      const authorization = `Basic ${btoa(`${auth.username}:${auth.password}`)}`
    
      const currentResponse = await fetch(url, {
        headers: {
          Authorization: authorization,
          Accept: "application/yang-data+json",
        },
      })
      let current: any = null
      if (currentResponse.ok) {
        current = currentResponse.status === 204 ? {} : await currentResponse.json()
      } else if (currentResponse.status !== 404) {
        throw new Error(`${currentResponse.status} ${await currentResponse.text()}`)
      }
    
      const changes = diff(intended, current ?? {}, "", [])
      if (changes.length === 0 || dry_run !== false) {
        return { changed: changes.length > 0, diff: changes, applied: false }
      }
    
      // PATCH merges into an existing resource; when the path holds no data yet,
      // PUT creates it (RFC 8040 sections 4.5 and 4.6.1). Leaves that already match
      // are rewritten with the same value, which changes nothing.
      const method = current === null ? "PUT" : "PATCH"
      const response = await fetch(url, {
        method,
        headers: {
          Authorization: authorization,
          "Content-Type": "application/yang-data+json",
          Accept: "application/yang-data+json",
        },
        body: JSON.stringify(intended),
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return { changed: true, diff: changes, applied: true, method }
    }
    

    Submitted by hugo989 2 hours ago