/
opflex_agent_cni.py
executable file
·143 lines (120 loc) · 4.71 KB
/
opflex_agent_cni.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
#
# 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.
# CNI plugin executable for OpFlex Agent container integration
import sys
import os
import logging
import shutil
import subprocess
import simplejson as json
from constants.logging import *
from constants.cni import *
import six
import __future__
if six.PY2:
from compat import shutilwhich
else:
from shutil import which as shutilwhich
errors = {
'PARAM': 100,
'INPUT': 101,
'PATH': 102,
'OS': 103,
'IPAM': 104
}
_log = logging.getLogger("opflex-agent-cni")
# Handle an error by logging it, outputting a properly-formatted error
# response, and exiting with the provided status code
def handleError(message, code, details=None):
_log.error("(%s) %s: %s", code, message, details)
json.dump({"cniVersion": CNI_VERSION,
"code": code,
"msg": message,
"details": details}, sys.stdout, indent=2, sort_keys=True)
print('')
sys.exit(code)
# Execute the IPAM plugin to get IP address information
def executeIPAM(netconfig):
path=os.environ.get('CNI_PATH', os.environ.get('PATH', os.defpath))
cniexe = netconfig['ipam']['type']
exe = shutilwhich(cniexe, path=path)
if exe is None:
handleError("Could not find CNI plugin executable", errors['PATH'],
"%s not found in %s" % (cniexe, path))
try:
_log.debug("Running IPAM module \"%s\"" % exe)
proc = subprocess.Popen([exe],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=True)
try:
(ipamres, ipamerr) = proc.communicate(input=json.dumps(netconfig))
result = json.loads(ipamres)
if proc.returncode != 0:
details = (result.get("details", "[No Details]") +
"\nStandard Error:" + ipamerr)
handleError("Error executing IPAM module", errors['IPAM'],
"(%d) %s: %s" %
(result.get("code", -1),
result.get("msg", "[No Message]"),
details))
finally:
if proc.returncode is None:
proc.kill()
proc.wait()
return result
except OSError as e:
handleError("Could not execute IPAM module %s" % exe, errors['OS'],
repr(e))
except json.JSONDecodeError as e:
handleError("Could not decode IPAM module output: %s" % exe, errors['INPUT'],
str(e))
except Exception as e:
handleError("Error executing IPAM module: %s" % exe, errors['IPAM'],
repr(e))
def cni_main():
log_level = os.environ.get("LOG_LEVEL", "info").upper()
formatter = logging.Formatter(LOG_FORMAT)
stdout_hdlr = logging.StreamHandler(sys.stderr)
stdout_hdlr.setFormatter(formatter)
_log.addHandler(stdout_hdlr)
_log.setLevel(log_level)
try:
netconfig = json.load(sys.stdin)
except json.JSONDecodeError as e:
handleError("Invalid JSON input", 101, str(e))
_log.debug('CNI configuration: Container ID: %s, '
'Interface Name: %s, '
'Network Namespace: %s, '
'Config: %s',
os.environ.get('CNI_CONTAINERID', None),
os.environ.get('CNI_IFNAME', None),
os.environ.get('CNI_NETNS', None),
netconfig)
for p in ['CNI_CONTAINERID', 'CNI_IFNAME', 'CNI_NETNS']:
if p not in os.environ:
handleError("Missing required environment variable",
errors['PARAM'], p)
for p in ['name', 'ipam']:
if p not in netconfig:
handleError("Missing required configuration parameter",
errors['PARAM'], p)
if "type" not in netconfig['ipam']:
handleError("Missing required IPAM configuration parameter",
errors['PARAM'], "type")
ipamresult = executeIPAM(netconfig)
json.dump(ipamresult, sys.stdout, indent=2, sort_keys=True)
print('')
if __name__ == "__main__":
cni_main()