PYTHON · Code cell
# =====================================================================
# P43 | Code cell 03 | Lab 43 · MQTT → Telegraf → InfluxDB
# Purpose: 3. Real-service installation, health checks and API implementation This code defines the optional stack. APT verifies repository signatures and package hashes; packages are extracted into temporary directories.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
"""Opt-in full service acceptance. No fallback: external errors are visible.
Run in a disposable Linux Colab runtime, or use already installed local binaries.
Requires signed apt packages, InfluxDB OSS 2.x (Flux), Telegraf, Grafana OSS.
"""
import base64, subprocess, tempfile, shutil
from urllib.error import HTTPError, URLError
# Define the reusable operation http; keep its logic separate from the trial.
def http(base,path,body=None,headers=None,method=None):
h=dict(headers or {})
if isinstance(body,dict):body=json.dumps(body).encode();h.setdefault('Content-Type','application/json')
req=Request(base+path,data=body,headers=h,method=method)
with urlopen(req,timeout=12) as r:return r.status,r.read()
# Define the reusable operation jhttp; keep its logic separate from the trial.
def jhttp(base,path,body=None,headers=None):return json.loads(http(base,path,body,headers)[1])
# Define the reusable operation free port; keep its logic separate from the trial.
def free_port():
with socket.socket() as s:s.bind(('127.0.0.1',0));return s.getsockname()[1]
# Fetch actual vendor .deb packages via signed apt indexes, extract in scratch space.
def provision_binaries(root,required,download=False):
"""Fetch actual vendor .deb packages via signed apt indexes, extract in scratch space.
No system-wide services or Docker, no unverified binary installation.
"""
root=Path(root);out={};packages={'influxd':'influxdb2','telegraf':'telegraf','grafana':'grafana'}
if not download:
for name in required:
candidates=[shutil.which(name)]
if name=='grafana':candidates+=['/usr/share/grafana/bin/grafana']
p=next((Path(c).resolve() for c in candidates if c and Path(c).is_file()),None)
check(p is not None,f'{name} missing: install vendor package or enable DOWNLOAD_SERVICES in disposable Colab');out[name]=p
return out
check(os.name=='posix' and shutil.which('apt-get') and shutil.which('gpg') and shutil.which('dpkg-deb'),'Linux apt, gpg and dpkg-deb required')
root.mkdir(parents=True,exist_ok=True);root.chmod(0o755);(root/'lists/partial').mkdir(parents=True);(root/'packages').mkdir();(root/'etc').mkdir()
sources=[]
repos=[('influx','https://repos.influxdata.com/influxdata-archive.key','24C975CBA61A024EE1B631787C3D57159FC2F927','https://repos.influxdata.com/debian')]
if 'grafana' in required:repos.append(('grafana','https://apt.grafana.com/gpg-full.key','B53AE77BADB630A683046005963FA27710458545','https://apt.grafana.com'))
for name,url,fpr,repo in repos:
key=root/'etc'/f'{name}.asc';key.write_bytes(urlopen(url,timeout=30).read())
fingerprints=subprocess.check_output(['gpg','--batch','--show-keys','--with-colons',str(key)],text=True,stderr=subprocess.DEVNULL)
check(any(line.startswith('fpr:') and line.split(':')[9]==fpr for line in fingerprints.splitlines()),f'{name} signing key changed: review official installation instructions')
# APT accepts an ASCII-armored keyring plus an explicit signing fingerprint.
sources.append(f'deb [signed-by={key},{fpr}] {repo} stable main')
src=root/'etc/sources.list';src.write_text('\n'.join(sources)+'\n')
opts=['-o',f'Dir::Etc::sourcelist={src}','-o','Dir::Etc::sourceparts=-','-o',f'Dir::State::lists={root/"lists"}','-o','APT::Get::List-Cleanup=0','-o','Acquire::Retries=1','-o','Acquire::https::Timeout=30','-o','Acquire::AllowInsecureRepositories=false','-o','APT::Get::AllowUnauthenticated=false']
subprocess.run(['apt-get',*opts,'update'],check=True,timeout=180)
for name in required:
dest=root/'packages'/name;dest.mkdir();subprocess.run(['apt-get',*opts,'download',packages[name]],cwd=dest,check=True,timeout=240)
deb=list(dest.glob('*.deb'));check(len(deb)==1,'expected one signed package');version=subprocess.check_output(['dpkg-deb','-f',str(deb[0]),'Version'],text=True).strip();print(packages[name],version)
extracted=dest/'extracted';subprocess.run(['dpkg-deb','-x',str(deb[0]),str(extracted)],check=True,timeout=180)
paths=[p for p in extracted.rglob(name) if p.is_file() and os.access(p,os.X_OK) and not p.is_symlink()];check(bool(paths),name+' executable missing');out[name]=paths[0]
return out
# Define the reusable operation service; keep its logic separate from the trial.
@contextlib.contextmanager
def service(cmd,root,env=None):
# Private transient process; no service manager, no public bind, no credential logs exported.
with open(Path(root)/('process-'+uuid.uuid4().hex+'.txt'),'wb') as log:
proc=subprocess.Popen([str(c) for c in cmd],stdout=log,stderr=subprocess.STDOUT,env=env)
try:yield proc
finally:
if proc.poll() is None:
proc.terminate()
try:proc.wait(timeout=8)
except subprocess.TimeoutExpired:proc.kill();proc.wait(timeout=5)
# Define the reusable operation await ready; keep its logic separate from the trial.
def await_ready(proc,fn,seconds=45):
deadline=time.monotonic()+seconds
while time.monotonic()<deadline:
check(proc.poll() is None,'service exited before readiness; check dependencies and vendor version')
try:return fn()
except (HTTPError,URLError,OSError,ValueError):time.sleep(.5)
raise RuntimeError('service readiness timeout')
# Define the reusable operation flux for; keep its logic separate from the trial.
def flux_for(run,field):
check(len(run)==32 and all(c in '0123456789abcdef' for c in run),'bad run id');check(field in ('temperature','humidity','soil_moisture','fan'),'bad field')
return f'from(bucket: "greenhouse") |> range(start: -1h) |> filter(fn: (r) => r._measurement == "environment" and r.run == "{run}" and r._field == "{field}") |> sort(columns: ["_time"])'
# Define the reusable operation influx values; keep its logic separate from the trial.
def influx_values(base,token,query):
_,b=http(base,'/api/v2/query?org=psut',{'query':query,'type':'flux'},{'Authorization':'Token '+token,'Accept':'application/csv'})
# Annotated CSV may contain multiple tables and repeated headers.
result=[];header=None
for row in csv.reader(io.StringIO(b.decode())):
if not row or row[0].startswith('#'):continue
if '_value' in row and '_time' in row:header=row;continue
if header and len(row)==len(header) and row[header.index('_value')]:result.append(float(row[header.index('_value')]))
return result
# Define the reusable operation line protocol; keep its logic separate from the trial.
def line_protocol(r):
return (f'environment,run={r["run"]},node={r["node"]},source=virtual '
f'temperature={float(r["temperature"])},humidity={float(r["humidity"])},soil_moisture={float(r["soil_moisture"])},fan={int(r["fan"])}i,seq={int(r["seq"])}i {r["ts"]}')
# Define the reusable operation grafana spec; keep its logic separate from the trial.
def grafana_spec(run):
ds={'type':'influxdb','uid':'psut-influx'}
panels=[]
for i,field in enumerate(('temperature','humidity','soil_moisture','fan')):
panels.append({'id':i+1,'type':'timeseries','title':field.replace('_',' ').title(),'datasource':ds,'gridPos':{'x':12*(i%2),'y':8*(i//2),'w':12,'h':8},'targets':[{'refId':'A','datasource':ds,'query':flux_for(run,field)}],'fieldConfig':{'defaults':{'unit':'celsius' if field=='temperature' else 'percent' if field!='fan' else 'none'},'overrides':[]}})
return {'uid':'psut-virtual-iot','title':'PSUT virtual greenhouse','schemaVersion':39,'version':0,'time':{'from':'now-1h','to':'now'},'panels':panels}
# Define the reusable operation telegraf config; keep its logic separate from the trial.
def telegraf_config(topic,base):
# Credentials are injected through a private environment, not printed or persisted.
return f'''[agent]
flush_interval = "1s"
omit_hostname = true
[[inputs.mqtt_consumer]]
servers = ["ssl://broker.hivemq.com:8883"]
topics = ["{topic}"]
qos = 1
client_id = "psut-telegraf-{uuid.uuid4().hex[:12]}"
persistent_session = false
topic_tag = ""
data_format = "json"
name_override = "environment"
tag_keys = ["run", "node", "source"]
json_time_key = "ts"
json_time_format = "unix"
[[outputs.influxdb_v2]]
urls = ["{base}"]
token = "${{PSUT_INFLUX_TOKEN}}"
organization = "psut"
bucket = "greenhouse"
'''
# Execute genuine service path. Raises on any missing component or mismatch.
def actual_stack(use_telegraf=True,use_grafana=True,download=False,count=12,threshold=27):
"""Execute genuine service path. Raises on any missing component or mismatch.
Virtual readings only; MQTT topic is unique and public. No secret in payload.
"""
rows=samples(count,threshold);run=rows[0]['run'];topic=f'psut/colab/{run}/telemetry';expected=[r['temperature'] for r in rows]
# Separate cache directory permits APT's sandbox user to read signing files.
with tempfile.TemporaryDirectory(prefix='psut-binaries-') as binary_dir,tempfile.TemporaryDirectory(prefix='psut-private-') as private:
Path(binary_dir).chmod(0o755);root=Path(private);required=['influxd']+(['telegraf'] if use_telegraf else [])+(['grafana'] if use_grafana else []);bins=provision_binaries(Path(binary_dir)/'vendor',required,download)
base=f'http://127.0.0.1:{free_port()}';token=secrets.token_hex(32);password=secrets.token_urlsafe(24)
with contextlib.ExitStack() as stack:
influx=stack.enter_context(service([bins['influxd'],'--http-bind-address',base.removeprefix('http://'),'--bolt-path',root/'influx.bolt','--engine-path',root/'engine','--reporting-disabled'],root))
await_ready(influx,lambda:jhttp(base,'/health'))
jhttp(base,'/api/v2/setup',{'username':'psut','password':password,'org':'psut','bucket':'greenhouse','token':token})
print('InfluxDB setup and health: OK')
if use_telegraf:
cfg=root/'telegraf.conf';cfg.write_text(telegraf_config(topic,base));env=dict(os.environ,PSUT_INFLUX_TOKEN=token)
tg=stack.enter_context(service([bins['telegraf'],'--config',cfg],root,env));time.sleep(4);check(tg.poll() is None,'Telegraf failed to start')
# Second subscriber verifies public broker delivery independently of Telegraf.
with MQTT('broker.hivemq.com',8883,True) as sub,MQTT('broker.hivemq.com',8883,True) as pub:
sub.subscribe(topic)
for r in rows:
payload=json.dumps(r,allow_nan=False).encode();pub.publish(topic,payload);t,b=sub.receive();check(t==topic and b==payload,'MQTT delivery mismatch')
else:
status,_=http(base,'/api/v2/write?org=psut&bucket=greenhouse&precision=s','\n'.join(map(line_protocol,rows)).encode(),{'Authorization':'Token '+token,'Content-Type':'text/plain; charset=utf-8'});check(status==204,'write not acknowledged')
q=flux_for(run,'temperature');deadline=time.monotonic()+35;values=[]
while time.monotonic()<deadline:
values=influx_values(base,token,q)
if len(values)>=count:break
time.sleep(1)
check(len(values)==count and all(math.isclose(a,b,abs_tol=1e-6) for a,b in zip(values,expected)),'InfluxDB count/value mismatch; no service PASS')
observed={'temperature':values}
for field in ('humidity','soil_moisture','fan'):
actual_field=influx_values(base,token,flux_for(run,field));check(len(actual_field)==count and all(math.isclose(a,b[field],abs_tol=1e-6) for a,b in zip(actual_field,rows)),field+' readback mismatch');observed[field]=actual_field
print('InfluxDB actual readback:',len(values),'records in each of four fields')
dashboard=grafana_spec(run);grafana_count=None
if use_grafana:
gf=f'http://127.0.0.1:{free_port()}';gp=bins['grafana'];home=gp.parent.parent if (gp.parent.parent/'conf/defaults.ini').exists() else Path('/usr/share/grafana');check((home/'conf/defaults.ini').is_file(),'Grafana homepath missing')
provision=root/'provisioning';provision.mkdir();env=dict(os.environ,GF_SERVER_HTTP_ADDR='127.0.0.1',GF_SERVER_HTTP_PORT=gf.split(':')[-1],GF_PATHS_DATA=str(root/'grafana-data'),GF_PATHS_LOGS=str(root/'grafana-logs'),GF_PATHS_PLUGINS=str(root/'grafana-plugins'),GF_PATHS_PROVISIONING=str(provision),GF_SECURITY_ADMIN_USER='psut',GF_SECURITY_ADMIN_PASSWORD=password,GF_AUTH_ANONYMOUS_ENABLED='false',GF_ANALYTICS_REPORTING_ENABLED='false',GF_ANALYTICS_CHECK_FOR_UPDATES='false',GF_PLUGINS_PREINSTALL_AUTO_UPDATE='false')
gfproc=stack.enter_context(service([gp,'server','--homepath',home],root,env));await_ready(gfproc,lambda:jhttp(gf,'/api/health'),75)
auth={'Authorization':'Basic '+base64.b64encode(('psut:'+password).encode()).decode()}
ds={'name':'PSUT InfluxDB','type':'influxdb','uid':'psut-influx','access':'proxy','url':base,'jsonData':{'version':'Flux','organization':'psut','defaultBucket':'greenhouse'},'secureJsonData':{'token':token}}
jhttp(gf,'/api/datasources',ds,auth);jhttp(gf,'/api/dashboards/db',{'dashboard':dashboard,'overwrite':True},auth)
saved=jhttp(gf,'/api/dashboards/uid/psut-virtual-iot',headers=auth);check(len(saved['dashboard']['panels'])==4,'dashboard readback failed')
result=jhttp(gf,'/api/ds/query',{'from':'now-1h','to':'now','queries':[{'refId':'A','datasource':{'type':'influxdb','uid':'psut-influx'},'query':q,'maxDataPoints':1000,'intervalMs':1000}]},auth)
a=result['results']['A'];check(not a.get('error') and a.get('status',200)==200,'Grafana query error');actual=[]
for frame in a.get('frames',[]):
for i,field in enumerate(frame['schema']['fields']):
if field.get('type')=='number':actual.extend(frame['data']['values'][i])
check(len(actual)==count and all(math.isclose(x,y,abs_tol=1e-6) for x,y in zip(actual,expected)),'Grafana query readback mismatch');grafana_count=len(actual);print('Grafana dashboard and datasource query: OK')
evidence={'schema':'psut-iot-stack-v2077','transport':'HiveMQ TLS / Telegraf' if use_telegraf else 'InfluxDB HTTP','storage':'actual InfluxDB OSS 2','source':'virtual','run':run,'rows':[[r['seq'],r['ts'],values[i],observed['humidity'][i],observed['soil_moisture'][i],observed['fan'][i]] for i,r in enumerate(rows)],'stored':len(values),'grafana_count':grafana_count,'dashboard':dashboard,'status':'passed'}
# Write only non-secret evidence; local services are stopped before leaving.
Path('psut-grafana-dashboard.json').write_text(json.dumps(dashboard,indent=2));Path('psut-stack-evidence.json').write_text(json.dumps(evidence,indent=2));return evidence