update-public-ip/index.js

76 lines
2.4 KiB
JavaScript
Raw Normal View History

2020-10-11 16:54:58 -07:00
import opts from 'config'
import Notifier from '@uci-utils/notify'
import Route53 from '@uci-utils/route53'
import pIp from 'public-ip'
import { lookup as clookup } from 'dns'
import { promisify } from 'util'
const lookup = promisify(clookup)
import { CronJob } from 'cron'
console.log(JSON.stringify(opts, null, 3))
const rname = process.argv[2] || opts.domain
if (!rname) {
console.log('exiting, must supply subdomain record name to check')
process.exit()
}
const interval = (opts.lookup || {}).interval * 1000 || 10000
const timeout = (opts.lookup || {}).timeout * 1000 * 60 || 120000
let notify=()=>{} // noop
const route53 = new Route53(opts.aws ? opts.aws : {profile:'default'})
;
(async () => {
if (opts.notify){
const notifier = await Notifier.create(opts.notify)
notify = notifier.send.bind(notifier)
}
if (opts.cron) {
console.log('setting up check cron job every', opts.cron,'minutes')
const cronstr = `0 */${opts.cron} * * * *`
const job = new CronJob(cronstr, checkIP)
console.log('cron job starting with:',cronstr)
job.start()
} else {
console.log('running check a single time')
checkIP
}
})().catch(err => {
console.log('FATAL: IP Updater! \n',err)
process.exitCode = 1
process.kill(process.pid, 'SIGINT') // this will restart via systemd unit
})
async function checkIP () {
let curr = await pIp.v4()
if (opts.dev) {
let ip = curr.split('.')
ip[0] = ip[0] - Math.floor(Math.random() * 10)
curr = ip.join('.')
}
const saved = await route53.getZoneRecordValue(rname)
if (opts.announce) notify('checking for change in public ip')
if (curr !== saved) {
let msg=`For Network:${opts.network}, a new public ip has been detected for ${rname} from ${saved} to ${curr}`
console.log(msg)
notify(msg)
msg=JSON.stringify(await route53.updateZoneRecordValue(rname,curr),null,3)
console.log(msg)
notify(msg)
const check = setInterval(async ()=>{
if (curr === (await lookup(rname)).address) {
msg=`Update Succeeded, lookup of ${rname} is now ${curr}`
clearInterval(check)
} else msg=`Update Pending, will check again in ${(opts.lookup || {}).interval || 10 } seconds`
console.log(msg)
notify(msg)
}
,(opts.lookup || {}).interval * 1000 || 10000)
// const fail = setTimeout(,timeout)
} else console.log('Public IP has not changed, nothing to do', saved)
}