Remove wrs-server-group SDK Module from StarlingX

With the StarlingX move to supporting pure upstream OpenStack, the
majority of the SDK Modules are related to functionality no longer
supported. The remaining SDK Modules will be moved to StarlingX
documentation.

Story: 2005275
Task: 30205

Change-Id: Ic0365f07297f0094b46c59d0fc6a62130c681f1e
Signed-off-by: Kristine Bujold <kristine.bujold@windriver.com>
This commit is contained in:
Kristine Bujold 2019-03-27 10:32:21 -04:00
parent bec66cfce8
commit 1ec6ba402b
39 changed files with 0 additions and 5136 deletions

View File

@ -9,5 +9,3 @@
# guest-client # guest-client
guest-client guest-client
# host-guest-comm
guest-host-comm

View File

@ -9,5 +9,3 @@
# guest-client # guest-client
guest-client guest-client
# host-guest-comm
guest-host-comm

View File

@ -2,9 +2,6 @@
# If these have dependencies, they will be pulled in automatically # If these have dependencies, they will be pulled in automatically
# #
# host-guest-comm
host-guest-comm
# nfv # nfv
nfv nfv
nfv-common nfv-common

View File

@ -1,6 +1,5 @@
nova-api-proxy nova-api-proxy
guest-client guest-client
guest-agent guest-agent
guest-comm
nfv nfv
mtce-guest mtce-guest

View File

@ -35,11 +35,6 @@ MTCE_GUEST_DIR=$STXNFV_DIR/mtce-guest
MTCE_GUEST_CONF=$STXNFV_SYSCONFDIR/mtc MTCE_GUEST_CONF=$STXNFV_SYSCONFDIR/mtc
MTCE_GUEST_OCF_DIR=$STXNFV_OCF_ROOT/resource.d/platform MTCE_GUEST_OCF_DIR=$STXNFV_OCF_ROOT/resource.d/platform
# guest-comm
GUEST_COMM_DIR=$STXNFV_DIR/guest-comm
HOST_AGENT_COMM_VER="2.0"
HOST_AGENT_COMM_DIR=$GUEST_COMM_DIR/host-guest-comm-$HOST_AGENT_COMM_VER
# guest-client # guest-client
GUEST_CLIENT_VERSION="3.0.1" GUEST_CLIENT_VERSION="3.0.1"

View File

@ -49,11 +49,5 @@ if is_service_enabled guest-agent || is_service_enabled guest-server; then
done done
fi fi
if is_service_enabled guest-scale-helper; then
# guest-scale-helper needs header files and libraries built from the folder
# guest-comm
enable_service host-agent
fi
# Initial source of lib script # Initial source of lib script
source $DEST/stx-nfv/devstack/lib/stx-nfv source $DEST/stx-nfv/devstack/lib/stx-nfv

View File

@ -1,12 +0,0 @@
Metadata-Version: 1.1
Name: host-guest-comm
Version: 2.0
Summary: Titanium Cloud host guest messaging agents, lib, apps
Home-page:
Author: Windriver
Author-email: info@windriver.com
License: Apache-2.0
Description: Titanium Cloud host guest messaging agents, lib, apps
Platform: UNKNOWN

View File

@ -1,2 +0,0 @@
SRC_DIR="host-guest-comm-2.0"
TIS_PATCH_VER=6

View File

@ -1,174 +0,0 @@
Summary: Titanium Cloud host guest messaging agents, lib, apps
Name: host-guest-comm
Version: 2.0
Release: %{tis_patch_ver}%{?_tis_dist}
License: Apache-2.0
Group: base
Packager: Wind River <info@windriver.com>
URL: unknown
Source0: %{name}-%{version}.tar.gz
%define cgcs_sdk_deploy_dir /opt/deploy/cgcs_sdk
BuildRequires: json-c
BuildRequires: json-c-devel
BuildRequires: systemd-devel
Requires: rtld(GNU_HASH)
Requires: /bin/sh
Requires: /usr/bin/systemctl
%description
Titanium Cloud host/guest messaging agents, guest app library, guest app
%package -n guest-host-comm
Summary: Titanium Cloud host guest messaging agents, lib, apps
Group: base
Requires: rtld(GNU_HASH)
Requires(post): rtld(GNU_HASH)
Requires: systemd
Requires(post): systemd
Requires(preun): systemd
%description -n guest-host-comm
Titanium Cloud host/guest messaging agents, guest app library, guest app
%package -n guest-host-comm-dev
Summary: Titanium Cloud host guest messaging agents, lib, apps
Group: base
Requires: guest-host-comm
%description -n guest-host-comm-dev
Titanium Cloud host/guest messaging agents, guest app library, guest app
%package -n %{name}-cgts-sdk
Summary: Titanium Cloud host guest messaging SDK files
Group: devel
%description -n %{name}-cgts-sdk
Titanium Cloud host guest messaging SDK files
%package -n host-guest-comm-dbg
Summary: Titanium Cloud host guest messaging agents, lib, apps - Debugging files
Group: devel
%description -n host-guest-comm-dbg
Titanium Cloud host/guest messaging agents, guest app library, guest app. This
package contains ELF symbols and related sources for debugging purposes.
%package -n host-guest-comm-dev
Summary: Titanium Cloud host guest messaging agents, lib, apps - Development files
Group: devel
Requires: host-guest-comm = %{version}-%{release}
%description -n host-guest-comm-dev
Titanium Cloud host/guest messaging agents, guest app library, guest app This
package contains symbolic links, header files, and related items necessary
for software development.
%prep
%setup
%build
VER=%{version}
MAJOR=`echo $VER | awk -F . '{print $1}'`
MINOR=`echo $VER | awk -F . '{print $2}'`
PATCH=%{tis_patch_ver}
make all VER=${VER} MAJOR=${MAJOR} MINOR=${MINOR} PATCH=${PATCH}
%install
VER=%{version}
MAJOR=`echo $VER | awk -F . '{print $1}'`
MINOR=`echo $VER | awk -F . '{print $2}'`
PATCH=%{tis_patch_ver}
make install \
DESTDIR=%{buildroot} \
SYSCONFDIR=%{buildroot}%{_sysconfdir} \
UNITDIR=%{buildroot}%{_unitdir} \
LIBDIR=%{buildroot}%{_libdir} \
SDK_DEPLOY_DIR=%{buildroot}%{cgcs_sdk_deploy_dir} \
MAJOR=${MAJOR} MINOR=${MINOR} PATCH=${PATCH}
%post
/usr/bin/systemctl enable host_agent.service
%postun
/usr/bin/systemctl disable host_agent.service
%files
%defattr(-,root,root,-)
/usr/lib64/libhostguestmsg.so.2.0.%{tis_patch_ver}
/usr/lib64/libhostguestmsg.so.2.0
/usr/lib64/libhostguestmsg.so.2
/usr/sbin/host_agent
/etc/pmon.d/host_agent.conf
/etc/init.d/host_agent
%{_unitdir}/host_agent.service
%files -n guest-host-comm
%defattr(-,root,root,-)
/usr/lib64/libguesthostmsg.so.2.0.%{tis_patch_ver}
/usr/lib64/libguesthostmsg.so.2.0
/usr/lib64/libguesthostmsg.so.2
/usr/lib64/libservergroup.so.2.0.%{tis_patch_ver}
/usr/lib64/libservergroup.so.2.0
/usr/lib64/libservergroup.so.2
/usr/sbin/server_group_app
/usr/sbin/guest_agent
%{_unitdir}/guest-agent.service
%preun -n guest-host-comm
%systemd_preun guest-agent.service
%post -n guest-host-comm
%systemd_post guest-agent.service
/usr/bin/systemctl enable guest-agent.service >/dev/null 2>&1
%files -n guest-host-comm-dev
%defattr(-,root,root,-)
/usr/include/cgcs/guest_host_msg.h
/usr/lib64/libguesthostmsg.so.2.0.%{tis_patch_ver}
/usr/lib64/libguesthostmsg.so.2.0
/usr/lib64/libguesthostmsg.so.2
/usr/lib64/libguesthostmsg.so
/usr/lib64/libservergroup.so.2.0.%{tis_patch_ver}
/usr/lib64/libservergroup.so.2.0
/usr/lib64/libservergroup.so.2
/usr/lib64/libservergroup.so
%files -n host-guest-comm-dbg
%defattr(-,root,root,-)
/usr/src/debug/host-guest-comm-2.0/server_group_app.c
/usr/src/debug/host-guest-comm-2.0/server_group.c
/usr/src/debug/host-guest-comm-2.0/guest_agent.c
/usr/src/debug/host-guest-comm-2.0/lib_host_guest_msg.c
/usr/src/debug/host-guest-comm-2.0/host_guest_msg.c
/usr/src/debug/host-guest-comm-2.0/lib_guest_host_msg.c
/usr/src/debug/host-guest-comm-2.0/host_guest_msg_type.h
/usr/src/debug/host-guest-comm-2.0/host_instance_mgmt.h
/usr/src/debug/host-guest-comm-2.0/host_instance_mgmt.c
/usr/src/debug/host-guest-comm-2.0/guest_host_msg.h
/usr/src/debug/host-guest-comm-2.0/host_guest_msg.h
/usr/src/debug/host-guest-comm-2.0/host_agent.c
/usr/src/debug/host-guest-comm-2.0/server_group.h
%files -n host-guest-comm-dev
%defattr(-,root,root,-)
/usr/include/cgcs/host_guest_msg.h
/usr/lib64/libhostguestmsg.so.2.0.%{tis_patch_ver}
/usr/lib64/libhostguestmsg.so.2.0
/usr/lib64/libhostguestmsg.so.2
/usr/lib64/libhostguestmsg.so
%files -n %{name}-cgts-sdk
%{cgcs_sdk_deploy_dir}/wrs-server-group-%{version}.%{tis_patch_ver}.tgz

View File

@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

View File

@ -1,175 +0,0 @@
#
# Copyright(c) 2013-2016, Wind River Systems, Inc. All rights reserved.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Wind River Systems nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Note: if you change either Makefile or Makefile.sdk you need to manually
# do a "make clean" and then "make".
# Import the Makefile that we give to the customer so we eat our own dogfood
include Makefile.sdk
DESTDIR ?= /
SYSCONFDIR ?= /etc
UNITDIR ?= /usr/lib/systemd/system
LIBDIR ?= /usr/lib64
SDK_DEPLOY_DIR ?= /opt/deploy/cgcs_sdk
MAJOR ?= 2
MINOR ?= 0
VERSION ?= $(MAJOR).$(MINOR)
PATCH ?= 0
# This needs to be extended from what the customer will build.
EXECS += host_agent
BINEXECS=$(addprefix $(BINDIR)/, $(EXECS))
HOST_AGENT_SRCS = host_guest_msg.c host_agent.c host_instance_mgmt.c
HOST_AGENT_OBJ := $(patsubst %,$(ODIR)/%,$(HOST_AGENT_SRCS:.c=.o))
LIBHOSTGUESTMSG_SRCS := lib_host_guest_msg.c
LIBHOSTGUESTMSG_OBJ := $(patsubst %,$(ODIR)/%,$(LIBHOSTGUESTMSG_SRCS:.c=.o))
LIBHOSTGUESTMSG := hostguestmsg
LIBHOSTGUESTMSG_SO := $(patsubst %,lib%.so,$(LIBHOSTGUESTMSG))
LIBHOSTGUESTMSG_DEP := $(patsubst %,$(LIBDIR)/%,$(LIBHOSTGUESTMSG_SO))
LIBS= $(LIBHOSTGUESTMSG)
LIBDEPS:=$(patsubst %,$(LIBDIR)/lib%.so,$(LIBS))
EXPORT_SDK := wrs-server-group-$(MAJOR).$(MINOR).$(PATCH)
# Add the host build as a dependency to the SDK build
all: host_all
host_all: $(BINEXECS) $(LIBDEPS) sdk/$(EXPORT_SDK).tgz
OBJS = $(HOST_AGENT_OBJ)
DEPS = $(OBJS:.o=.d) sdk/sdk.d
-include $(DEPS)
# The dependency tracking for the SDK tarball is rather crude. If any
# file changes they're all copied over again. This is quick, so it's
# not worth getting fancy.
sdk/$(EXPORT_SDK).tgz:
@echo "Making SDK"
@mkdir -p sdk/$(EXPORT_SDK)
@mkdir -p sdk/$(EXPORT_SDK)/lib
@mkdir -p sdk/$(EXPORT_SDK)/bin
@mkdir -p sdk/$(EXPORT_SDK)/obj
@mkdir -p sdk/$(EXPORT_SDK)/scripts
@cp scripts/guest-agent.service sdk/$(EXPORT_SDK)/scripts
@echo "MAJOR=$(MAJOR)" > sdk/$(EXPORT_SDK)/Makefile
@echo "MINOR=$(MINOR)" >> sdk/$(EXPORT_SDK)/Makefile
@echo "PATCH=$(PATCH)" >> sdk/$(EXPORT_SDK)/Makefile
@cat Makefile.sdk >> sdk/$(EXPORT_SDK)/Makefile
@cp LICENSE sdk/$(EXPORT_SDK)
@cp docs/README.txt sdk/$(EXPORT_SDK)
@cp docs/TiS-Guest-Server-Group-Messaging.pdf sdk/$(EXPORT_SDK)
@cp $(GUEST_CLIENT_APP_SRCS) sdk/$(EXPORT_SDK)
@cp $(LIBSERVERGROUP_SRCS) sdk/$(EXPORT_SDK)
@cp $(LIBGUESTHOSTMSG_SRCS) sdk/$(EXPORT_SDK)
@cp $(GUEST_AGENT_SRCS) sdk/$(EXPORT_SDK)
@cp host_guest_msg_type.h server_group.h misc.h guest_host_msg.h sdk/$(EXPORT_SDK)
@cd sdk && tar czf $(EXPORT_SDK).tgz $(EXPORT_SDK)
@echo -n "sdk/$(EXPORT_SDK).tgz: Makefile.sdk docs/README.txt docs/TiS-Guest-Server-Group-Messaging.pdf " > sdk/sdk.d
@echo -n "scripts/guest-agent.service " >> sdk/sdk.d
@echo -n "$(GUEST_CLIENT_APP_SRCS) $(LIBSERVERGROUP_SRCS) $(GUEST_AGENT_SRCS) $(LIBGUESTHOSTMSG_SRCS)" >> sdk/sdk.d
@echo " host_guest_msg.h server_group.h misc.h" >> sdk/sdk.d
@echo '*' > sdk/.gitignore
$(LIBHOSTGUESTMSG_DEP): CFLAGS2 = -fPIC
$(LIBHOSTGUESTMSG_DEP): $(LIBHOSTGUESTMSG_OBJ)
$(CC) -shared -Wl,-soname,$(LIBHOSTGUESTMSG_SO).$(MAJOR) $^ -o $(LIBHOSTGUESTMSG_DEP).$(MAJOR).$(MINOR).$(PATCH)
ln -sf $(LIBHOSTGUESTMSG_SO).$(MAJOR).$(MINOR).$(PATCH) $(LIBHOSTGUESTMSG_DEP).$(MAJOR)
ln -sf $(LIBHOSTGUESTMSG_SO).$(MAJOR) $(LIBHOSTGUESTMSG_DEP)
$(BINDIR)/host_agent: $(HOST_AGENT_OBJ)
$(CC) -o $@ $^ $(LDFLAGS) -lrt -ljson-c
install:
install -m 750 -d $(DESTDIR)/usr/sbin
install -m 755 -d $(DESTDIR)/usr/lib64
install -m 755 -d $(DESTDIR)/usr/include
install -m 755 -d $(DESTDIR)/usr/include/cgcs
install -m 750 -d $(SYSCONFDIR)/init.d
install -m 750 -d $(SYSCONFDIR)/pmon.d
install -m 750 -d $(UNITDIR)
install -m 750 -d $(DESTDIR)/usr
install -m 750 -d $(DESTDIR)/usr/src
install -m 750 -d $(DESTDIR)/usr/src/debug
install -m 750 -d $(DESTDIR)/usr/src/debug/host-guest-comm-$(VERSION)
install -m 644 host_guest_msg_type.h $(DESTDIR)/usr/src/debug/host-guest-comm-$(VERSION)/host_guest_msg_type.h
install -m 644 server_group_app.c $(DESTDIR)/usr/src/debug/host-guest-comm-$(VERSION)/server_group_app.c
install -m 644 server_group.c $(DESTDIR)/usr/src/debug/host-guest-comm-$(VERSION)/server_group.c
install -m 644 guest_agent.c $(DESTDIR)/usr/src/debug/host-guest-comm-$(VERSION)/guest_agent.c
install -m 644 lib_host_guest_msg.c $(DESTDIR)/usr/src/debug/host-guest-comm-$(VERSION)/lib_host_guest_msg.c
install -m 644 host_guest_msg.c $(DESTDIR)/usr/src/debug/host-guest-comm-$(VERSION)/host_guest_msg.c
install -m 644 lib_guest_host_msg.c $(DESTDIR)/usr/src/debug/host-guest-comm-$(VERSION)/lib_guest_host_msg.c
install -m 644 host_instance_mgmt.h $(DESTDIR)/usr/src/debug/host-guest-comm-$(VERSION)/host_instance_mgmt.h
install -m 644 host_instance_mgmt.c $(DESTDIR)/usr/src/debug/host-guest-comm-$(VERSION)/host_instance_mgmt.c
install -m 644 guest_host_msg.h $(DESTDIR)/usr/src/debug/host-guest-comm-$(VERSION)/guest_host_msg.h
install -m 644 host_guest_msg.h $(DESTDIR)/usr/src/debug/host-guest-comm-$(VERSION)/host_guest_msg.h
install -m 644 host_agent.c $(DESTDIR)/usr/src/debug/host-guest-comm-$(VERSION)/host_agent.c
install -m 644 server_group.h $(DESTDIR)/usr/src/debug/host-guest-comm-$(VERSION)/server_group.h
install -m 750 scripts/host_agent $(SYSCONFDIR)/init.d/host_agent
install -m 644 scripts/host_agent.service $(UNITDIR)/host_agent.service
install -m 644 scripts/guest-agent.service $(UNITDIR)/guest-agent.service
install -m 640 scripts/host_agent.conf $(SYSCONFDIR)/pmon.d/host_agent.conf
install -m 750 bin/host_agent $(DESTDIR)/usr/sbin/host_agent
install -m 750 bin/guest_agent $(DESTDIR)/usr/sbin/guest_agent
install -m 750 bin/server_group_app $(DESTDIR)/usr/sbin/server_group_app
install -m 644 guest_host_msg.h $(DESTDIR)/usr/include/cgcs/guest_host_msg.h
install -m 644 host_guest_msg.h $(DESTDIR)/usr/include/cgcs/host_guest_msg.h
# Deploy to the SDK deployment directory
install -d $(SDK_DEPLOY_DIR)
install -m 644 sdk/wrs-server-group-$(VERSION).$(PATCH).tgz $(SDK_DEPLOY_DIR)/wrs-server-group-$(VERSION).$(PATCH).tgz
install -m 755 -p -D lib/libguesthostmsg.so.$(MAJOR).$(MINOR).$(PATCH) $(LIBDIR)/libguesthostmsg.so.$(MAJOR).$(MINOR).$(PATCH)
ln -s libguesthostmsg.so.$(MAJOR).$(MINOR).$(PATCH) $(LIBDIR)/libguesthostmsg.so.$(MAJOR).$(MINOR)
ln -s libguesthostmsg.so.$(MAJOR).$(MINOR).$(PATCH) $(LIBDIR)/libguesthostmsg.so.$(MAJOR)
ln -s libguesthostmsg.so.$(MAJOR).$(MINOR).$(PATCH) $(LIBDIR)/libguesthostmsg.so
install -m 755 -p -D lib/libhostguestmsg.so.$(MAJOR).$(MINOR).$(PATCH) $(LIBDIR)/libhostguestmsg.so.$(MAJOR).$(MINOR).$(PATCH)
ln -s libhostguestmsg.so.$(MAJOR).$(MINOR).$(PATCH) $(LIBDIR)/libhostguestmsg.so.$(MAJOR).$(MINOR)
ln -s libhostguestmsg.so.$(MAJOR).$(MINOR).$(PATCH) $(LIBDIR)/libhostguestmsg.so.$(MAJOR)
ln -s libhostguestmsg.so.$(MAJOR).$(MINOR).$(PATCH) $(LIBDIR)/libhostguestmsg.so
install -m 755 -p -D lib/libservergroup.so.$(MAJOR).$(MINOR).$(PATCH) $(LIBDIR)/libservergroup.so.$(MAJOR).$(MINOR).$(PATCH)
ln -s libservergroup.so.$(MAJOR).$(MINOR).$(PATCH) $(LIBDIR)/libservergroup.so.$(MAJOR).$(MINOR)
ln -s libservergroup.so.$(MAJOR).$(MINOR).$(PATCH) $(LIBDIR)/libservergroup.so.$(MAJOR)
ln -s libservergroup.so.$(MAJOR).$(MINOR).$(PATCH) $(LIBDIR)/libservergroup.so
# Add the host clean as a dependency to the SDK stuff
clean: host_clean
host_clean:
rm -rf sdk

View File

@ -1,118 +0,0 @@
#
# Copyright(c) 2013-2016, Wind River Systems, Inc. All rights reserved.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Wind River Systems nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
.PHONY: all clean
EXECS= guest_agent server_group_app
CFLAGS= -g -Wall -Wformat -Wformat-security
LDFLAGS =
ODIR=obj
BINDIR=bin
LIBDIR=lib
INCDIR=include/cgcs
_DEPS = *.h
DEPS = $(patsubst %,$(IDIR)/%,$(_DEPS))
GUEST_AGENT_SRCS = host_guest_msg.c guest_agent.c
GUEST_AGENT_OBJ := $(patsubst %,$(ODIR)/%,$(GUEST_AGENT_SRCS:.c=.o))
GUEST_CLIENT_APP_SRCS = server_group_app.c
GUEST_CLIENT_APP_OBJ := $(patsubst %,$(ODIR)/%,$(GUEST_CLIENT_APP_SRCS:.c=.o))
LIBGUESTHOSTMSG_SRCS := lib_guest_host_msg.c
LIBGUESTHOSTMSG_INCLUDES := guest_host_msg.h
LIBGUESTHOSTMSG_OBJ := $(patsubst %,$(ODIR)/%,$(LIBGUESTHOSTMSG_SRCS:.c=.o))
LIBGUESTHOSTMSG := guesthostmsg
LIBGUESTHOSTMSG_SO := $(patsubst %,lib%.so,$(LIBGUESTHOSTMSG))
LIBGUESTHOSTMSG_DEP := $(patsubst %,$(LIBDIR)/%,$(LIBGUESTHOSTMSG_SO))
LIBSERVERGROUP_SRCS := server_group.c
LIBSERVERGROUP_INCLUDES := server_group.h
LIBSERVERGROUP_OBJ := $(patsubst %,$(ODIR)/%,$(LIBSERVERGROUP_SRCS:.c=.o))
LIBSERVERGROUP := servergroup
LIBSERVERGROUP_SO := $(patsubst %,lib%.so,$(LIBSERVERGROUP))
LIBSERVERGROUP_DEP := $(patsubst %,$(LIBDIR)/%,$(LIBSERVERGROUP_SO))
LIBS= $(LIBSERVERGROUP) $(LIBGUESTHOSTMSG)
INCLUDES= $(LIBGUESTHOSTMSG_INCLUDES) $(LIBSERVERGROUP_INCLUDES)
BINEXECS=$(addprefix $(BINDIR)/, $(EXECS))
LIBDEPS:=$(patsubst %,$(LIBDIR)/lib%.so,$(LIBS))
INCDEPS:=$(addprefix $(INCDIR)/, $(INCLUDES))
all: $(BINEXECS) $(LIBDEPS) $(INCDIR) $(INCDEPS)
OBJS = $(GUEST_AGENT_OBJ) $(LIBSERVERGROUP_OBJ) $(GUEST_CLIENT_APP_OBJ)
DEPS = $(OBJS:.o=.d)
-include $(DEPS)
$(ODIR)/%.o: %.c
$(CC) -c $(CFLAGS) $(CFLAGS2) -MMD -o $@ $<
$(INCDIR):
mkdir -p $(INCDIR)
$(INCDIR)/%.h: %.h $(INCDIR)
cp $< $@
vpath %.h .
# the version of make in wrl5 seems to have a problem with target-specific
# variable values. It can't handle just doing "CFLAGS += -fPIC". Same thing
# for LDFLAGS below. This seems to work as a workaround.
$(LIBSERVERGROUP_DEP): CFLAGS2 = -fPIC
$(LIBSERVERGROUP_DEP): $(LIBSERVERGROUP_OBJ)
$(CC) -shared -Wl,-soname,$(LIBSERVERGROUP_SO).$(MAJOR) $^ -o $(LIBSERVERGROUP_DEP).$(MAJOR).$(MINOR).$(PATCH)
ln -sf $(LIBSERVERGROUP_SO).$(MAJOR).$(MINOR).$(PATCH) $(LIBSERVERGROUP_DEP).$(MAJOR)
ln -sf $(LIBSERVERGROUP_SO).$(MAJOR) $(LIBSERVERGROUP_DEP)
$(LIBGUESTHOSTMSG_DEP): CFLAGS2 = -fPIC
$(LIBGUESTHOSTMSG_DEP): $(LIBGUESTHOSTMSG_OBJ)
$(CC) -shared -Wl,-soname,$(LIBGUESTHOSTMSG_SO).$(MAJOR) $^ -o $(LIBGUESTHOSTMSG_DEP).$(MAJOR).$(MINOR).$(PATCH)
ln -sf $(LIBGUESTHOSTMSG_SO).$(MAJOR).$(MINOR).$(PATCH) $(LIBGUESTHOSTMSG_DEP).$(MAJOR)
ln -sf $(LIBGUESTHOSTMSG_SO).$(MAJOR) $(LIBGUESTHOSTMSG_DEP)
$(BINDIR)/guest_agent: LDFLAGS2 = -rdynamic
$(BINDIR)/guest_agent: $(GUEST_AGENT_OBJ)
$(CC) -o $@ $^ $(LDFLAGS) $(LDFLAGS2) -ljson-c
$(BINDIR)/server_group_app: LDFLAGS2 = -l$(LIBSERVERGROUP) -L$(LIBDIR)
$(BINDIR)/server_group_app: $(GUEST_CLIENT_APP_OBJ) $(LIBSERVERGROUP_DEP)
$(CC) -o $@ $^ $(LDFLAGS) $(LDFLAGS2) -ljson-c
clean:
rm -rf $(ODIR)/* *~ core $(BINDIR)/* $(LIBDIR)/*

View File

@ -1,4 +0,0 @@
# Ignore everything in this directory
*
# Except this file
!.gitignore

View File

@ -1,257 +0,0 @@
Copyright(c) 2013-2016, Wind River Systems, Inc.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Wind River Systems nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------
DESCRIPTION
===========
Server Group Messaging is a service to provide simple low-bandwidth datagram
messaging and notifications for servers that are part of the same server group.
This messaging channel is available regardless of whether IP networking is
functional within the server, and it requires no knowledge within the server
about the other members of the group.
The service provides three types of messaging:
1) Broadcast: this allows a server to send a datagram (size of up to 3050 bytes)
to all other servers within the server group.
2) Notification: this provides servers with information about changes to the
state of other servers within the server group.
3) Status: this allows a server to query the current state of all servers within
the server group (including itself).
This service is not intended for high bandwidth or low-latency operations. It
is best-effort, not reliable. Applications should do end-to-end acks and
retries if they care about reliability.
REQUIREMENTS
============
Compilation:
Linux OS, x86_64 architecture
gcc compiler
development libraries and headers for glibc
development libraries and headers for json-c
VM Runtime:
Linux OS, x86_64 architecture
runtime libraries for glibc
runtime libraries for json-c
The code has been tested with glibc 2.15, gcc 4.6 and json-c 0.12.99 but it
should run on other versions without difficulty.
DELIVERABLE
===========
The Server Group Messaging service is delivered as source with the
required makefiles in a compressed tarball called
"wrs-server-group-2.0.0.tgz", such that it can be compiled for the applicable
guest linux distribution.
COMPILE
=======
Install the prerequisites:
On CentOS/RHEL: yum install json-c-devel make gcc glibc-devel
On Ubuntu/Debian: sudo apt-get install build-essential libjson0-dev
Extract the tarball contents:
tar xvf wrs-server-group-#.#.#.tgz
To compile:
cd wrs-server-group-#.#.#
make
export WRS_SERVER_GROUP_DIR=${PWD}
This will produce:
1) An executable "bin/guest_agent". This acts as a relay between the guest and
the host. This executable must be installed into the guest and configured to
run at startup. It should be configured to respawn (via /etc/inittab or some
other process monitor) if it dies for any reason.
Typical manual installation commands:
sudo cp bin/* /usr/sbin
sudo cp scripts/guest-agent.service /lib/systemd/system/
sudo systemctl enable guest-agent.service
sudo systemctl start guest-agent.service
2) A library "lib/libservergroup.so.2.0.*". This encapsulates the details of
talking to the guest agent. This can be used with the header file
"server_group.h" to create custom applications that can make use of the
messaging service. This should be installed within the guest in a suitable
library location such that the linker can find it. It should also be installed
in the build system where custom applications can link against it. The
"libservergroup.so.2" symlink should be created in the build system and the
guest, and the "libservergroup.so" symlink should be created in the build
system, either by ldconfig or some other means.
Typical manual installation commands:
sudo cp -P lib/libservergroup.* /usr/lib/
sudo ldconfig
3) A header file "include/cgcs/server_group.h". This is used along with the library to
create custom applications that can make use of the messaging service. This
should be installed in the build system where custom applications can include
it.
4) A sample program "bin/server_group_app" is created in order to show the use
of the APIs and validate that they are working properly in the guest.
5) A library "lib/libguesthostmsg.so.2.0.*". This library is used by
wrs-guest-scale component packaged separately. This can be used with the
header file "guest_host_msg.h". This should be installed within
the guest in a suitable library location such that the linker can find it.
It should also be installed in the build system where custom applications can
link against it. The "libguesthostmsg.so.2" symlink should be created in the
build system and the guest, and the "libguesthostmsg.so" symlink should be
created in the build system, either by ldconfig or some other means.
Typical manual installation commands:
sudo cp -P lib/libguesthostmsg.* /usr/lib/
sudo ldconfig
6) A header file "include/cgcs/guest_host_msg.h". This is used along with
the library to create custom applications that can make use of the messaging
service. This should be installed in the build system where custom
applications can include it. (Setting the WRS_SERVER_GROUP_DIR environment as above
variable will allow it to be found when building the wrs-guest-scale component.)
Note:
The inclusion of the files into the build system and the guest image and the
configuration of the guest startup scripts is left up to the user to allow for
different build systems and init subsystems in the guest.
INSTALL
=======
Installing in a running VM:
As the root user
1) Copy "bin/guest_agent" and any other desired binaries such as
"bin/server_group_app" to /usr/sbin in the VM.
2) Run "cp -P lib/* /usr/lib" (or /usr/lib64 as appropriate) in the VM
to install the libraries.
3) Run "ldconfig".
4) Copy scripts/guest-agent.service to /lib/systemd/system/ and then run
"systemctl enable guest-agent.service" and "systemctl start guest-agent.service".
This should cause the "guest-agent" binary to start running.
5) Applications can now make use of the service.
6) Run "cp -r include/cgcs /usr/include/" to set up the headers for anyone
wanting to link against libservergroup or libguesthostmsg.
As part of building the VM ISO Image:
1) Ensure "bin/guest_agent" and any other desired binaries get installed
to /usr/sbin in the VM filesystem.
2) Ensure "lib/*" gets installed to /usr/lib64 in the VM filesystem.
3) Ensure that "ldconfig" will run at VM startup.
4) Ensure that "/usr/sbin/guest_agent" is configured to run automatically
at VM startup and to respawn if it dies for any reason. The scripts/
guest_agent.service file is provided for use by systemd.
USAGE
=====
The service is designed to be simple to use. A basic description is given
below, but more details are provided in the header file.
First, the application must call init_sg(). This call takes three function
pointers corresponding to callbacks for the various message types. If an
application doesn't intend to use one or more of the message types then the
appropriate function pointers can be specified as NULL. The function returns a
socket that must be monitored for activity using select/poll/etc.
When the socket becomes readable, the application must call process_sg_msg().
This may result in callbacks being called so be careful about deadlock.
In order to send a broadcast message to every server in the server group, the
application can call sg_msg_broadcast().
In order to request the status of all servers in the group, the application can
call sg_request_status().
The sg_broadcast_msg_handler_t() callback will be called when receiving a server
group broadcast message. It will be passed the message as well as a
null-terminated string containing the instance name of the sender.
The sg_notification_msg_handler_t() callback will be called when receiving a
notification message indicating a status change in one of the members of the
server group. The msg is JSON-formatted, essentially the normal notification
that gets sent out by OpenStack's notification service, but with some
non-relevant information removed to keep the message shorter.
The sg_status_msg_handler_t() callback will be called when receiving the
response to a status query. The message is a JSON-formatted list of
dictionaries, each of which represents a single server.
SAMPLE APPLICATION
==================
The "server_group_app" sample application can be used to test the various types
of messages. It takes one optional argument, consisting of a character string
in quotes. When run, it behaves as follows:
1) It registers for all three callbacks.
2) If the optional argument was specified it sends that string as a server group
broadcast message.
3) It requests the group status.
4) It then goes into a loop waiting for incoming messages. Any incoming message
will be printed out along with information about the type of message.
The service can be validated as follows using the "server_group_app" sample
application:
a) Create a server group with the "affinity" scheduler policy.
b) Start up a server within the server group.
c) Run "server_group_app" in the first server. You should immediately see the
status response message containing information about that server.
d) Start up a second server within the server group. You should see
notification messages being received in the first server.
e) Run 'server_group_app "this is a test"' on the second server. You should see
"this is a test" received as a broadcast message on the first server. The
second server should show a status response with information about both
servers
f) Start up a third server within the server group. You should see
notification messages being received in the other two servers.
g) Run 'server_group_app "final test"' on the second server. You should see
"final test" received as a broadcast message on the other two servers. The
second server should show a status response with information about all three
servers

View File

@ -1,503 +0,0 @@
/*
* Copyright (c) 2013-2016, Wind River Systems, Inc.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3) Neither the name of Wind River Systems nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
*/
#define _GNU_SOURCE /* for memmem() */
#include <stddef.h>
#include <errno.h>
#include <error.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/select.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <syslog.h>
#include <limits.h>
#include <signal.h>
#include <execinfo.h>
#include <json-c/json.h>
#include "host_guest_msg_type.h"
/*
Notes on virtio-serial in guest:
1) The fact that POLLHUP is always set in revents when host connection is down
means that the only way to get event-driven notification of connection is to
register for SIGIO. However, then we get a SIGIO every time the device becomes
readable. The solution is to selectively block SIGIO as long as we think the link
is up, then unblock it so we get notified when the link comes back.
2) If the host disconnects we will still process any buffered messages from it.
3) If read() returns 0 or write() returns -1 with errno of EAGAIN that means
the host is disconnected.
*/
// Tokener serves as reassembly buffer for host connection.
struct json_tokener* tok;
int host_fd;
int app_fd;
volatile sig_atomic_t check_host_connection=1;
volatile sig_atomic_t initial_connection=1;
// Currently we only use 2 fds, one for server group messaging and one for the
// connection to the host.
#define MAX_FDS_GUEST 10
// Message has arrived from the host.
// This assumes the message has been validated
void process_msg(json_object *jobj_msg, int fd)
{
int rc;
struct sockaddr_un cliaddr;
int addrlen;
// parse version
struct json_object *jobj_version;
if (!json_object_object_get_ex(jobj_msg, VERSION, &jobj_version)) {
PRINT_ERR("failed to parse version\n");
return;
}
int version = json_object_get_int(jobj_version);
if (version != CUR_VERSION) {
PRINT_ERR("received version %d, expected %d\n", version, CUR_VERSION);
return;
}
// parse source addr
struct json_object *jobj_source_addr;
if (!json_object_object_get_ex(jobj_msg, SOURCE_ADDR, &jobj_source_addr)) {
PRINT_ERR("failed to parse source_addr\n");
return;
}
// parse dest addr
struct json_object *jobj_dest_addr;
if (!json_object_object_get_ex(jobj_msg, DEST_ADDR, &jobj_dest_addr)) {
PRINT_ERR("failed to parse dest_addr\n");
return;
}
const char *dest_addr = json_object_get_string(jobj_dest_addr);
// parse msg data
struct json_object *jobj_data;
if (!json_object_object_get_ex(jobj_msg, DATA, &jobj_data)) {
PRINT_ERR("failed to parse data\n");
return;
}
//create outgoing message
struct json_object *jobj_outmsg = json_object_new_object();
if (jobj_outmsg == NULL) {
PRINT_ERR("failed to allocate json object for jobj_outmsg\n");
return;
}
json_object_object_add(jobj_outmsg, DATA, jobj_data);
json_object_object_add(jobj_outmsg, VERSION, json_object_new_int(CUR_VERSION));
json_object_object_add(jobj_outmsg, SOURCE_ADDR, jobj_source_addr);
const char *outmsg = json_object_to_json_string_ext(jobj_outmsg, JSON_C_TO_STRING_PLAIN);
// Set up destination address
memset(&cliaddr, 0, sizeof(struct sockaddr_un));
cliaddr.sun_family = AF_UNIX;
cliaddr.sun_path[0] = '\0';
strncpy(cliaddr.sun_path+1, dest_addr, strlen(dest_addr));
addrlen = sizeof(sa_family_t) + strlen(dest_addr) + 1;
// Send the message to the client.
// This will get transparently restarted if interrupted by signal.
ssize_t outlen = strlen(outmsg);
rc = sendto(app_fd, outmsg, outlen, 0, (struct sockaddr *) &cliaddr,
addrlen);
if (rc == -1) {
PRINT_ERR("unable to send msg to %.*s: %m\n", UNIX_ADDR_LEN, cliaddr.sun_path+1);
} else if (rc != outlen) {
PRINT_ERR("sendto didn't send the whole message\n");
}
json_object_put(jobj_outmsg);
}
void handle_app_msg(const char *msg, struct sockaddr_un *cliaddr,
socklen_t cliaddrlen)
{
int rc;
char *app_addr;
//parse incoming msg
struct json_object *jobj_msg = json_tokener_parse(msg);
if (jobj_msg == NULL) {
PRINT_ERR("failed to parse msg\n");
return;
}
// parse version
struct json_object *jobj_version;
if (!json_object_object_get_ex(jobj_msg, VERSION, &jobj_version)) {
PRINT_ERR("failed to parse version\n");
goto done;
}
int version = json_object_get_int(jobj_version);
if (version != CUR_VERSION) {
PRINT_ERR("message from app version %d, expected %d, dropping\n",
version, CUR_VERSION);
goto done;
}
// parse dest instance
struct json_object *jobj_dest_addr;
if (!json_object_object_get_ex(jobj_msg, DEST_ADDR, &jobj_dest_addr)) {
PRINT_ERR("failed to parse dest_address\n");
goto done;
}
// parse data
struct json_object *jobj_data;
if (!json_object_object_get_ex(jobj_msg, DATA, &jobj_data)) {
PRINT_ERR("failed to parse data\n");
goto done;
}
if (cliaddr->sun_path[0] == '\0') {
app_addr = cliaddr->sun_path+1;
// get length without family or leading null from abstract namespace
cliaddrlen = cliaddrlen - sizeof(sa_family_t) - 1;
app_addr[cliaddrlen] = '\0';
} else {
PRINT_INFO("client address not in abstract namespace, dropping\n");
goto done;
}
struct json_object *jobj_outmsg = json_object_new_object();
if (jobj_outmsg == NULL) {
PRINT_ERR("failed to allocate json object for outmsg\n");
goto done;
}
json_object_object_add(jobj_outmsg, DATA, jobj_data);
json_object_object_add(jobj_outmsg, VERSION, jobj_version);
json_object_object_add(jobj_outmsg, DEST_ADDR, jobj_dest_addr);
json_object_object_add(jobj_outmsg, SOURCE_ADDR, json_object_new_string(app_addr));
const char *outmsg = json_object_to_json_string_ext(jobj_outmsg, JSON_C_TO_STRING_PLAIN);
// use '\n' to delimit JSON string: mark the beginning
rc = write(host_fd, "\n", 1);
if (rc == -1) {
PRINT_ERR("unable to send \\n \n");
}
// send to host
ssize_t outlen = strlen(outmsg);
rc = write(host_fd, outmsg, outlen);
if (rc == -1) {
PRINT_ERR("unable to send msg from %.*s: %m\n", UNIX_ADDR_LEN, app_addr);
} else if (rc != outlen) {
PRINT_ERR("write didn't write the whole message to host\n");
}
// use '\n' to delimit JSON string: mark the ending
rc = write(host_fd, "\n", 1);
if (rc == -1) {
PRINT_ERR("unable to send \\n \n");
}
json_object_put(jobj_outmsg);
done:
json_object_put(jobj_msg);
}
void unmask_sigio(void)
{
sigset_t mask;
sigemptyset (&mask);
sigaddset (&mask, SIGIO);
sigprocmask(SIG_UNBLOCK, &mask, 0);
}
void mask_sigio(void)
{
sigset_t mask;
sigemptyset (&mask);
sigaddset (&mask, SIGIO);
sigprocmask(SIG_BLOCK, &mask, 0);
}
void handle_host_conn_down()
{
check_host_connection = 0;
unmask_sigio();
}
void scan_host_fd(struct pollfd *pfd)
{
char buf[10000];
ssize_t rc;
if (pfd->revents & POLLIN) {
// Read all messages from the host device
while(1) {
rc = read(pfd->fd, buf, sizeof(buf));
if (rc == 0) {
// Connection to host has gone down
handle_host_conn_down();
return;
} else if (rc < 0) {
if (errno == EAGAIN)
// We've read all the messages
return;
else {
PRINT_ERR("read from host: %m");
return;
}
}
handle_virtio_serial_msg(buf, rc, pfd->fd, tok);
}
}
}
void scan_app_fd(struct pollfd *pfd)
{
char buf[10000];
struct sockaddr_un cliaddr;
ssize_t rc;
// Read all messages from the app socket
if (pfd->revents & POLLIN) {
while(1) {
socklen_t addrlen = sizeof(struct sockaddr_un);
rc = recvfrom(pfd->fd, buf, sizeof(buf), 0,
(struct sockaddr *) &cliaddr, &addrlen);
if (rc < 0) {
if (errno == EAGAIN)
// We've read all the messages
return;
else {
PRINT_ERR("recvfrom from app: %m");
return;
}
}
handle_app_msg(buf, &cliaddr, addrlen);
}
}
}
//we get a SIGIO if the host connection connects/disconnects
static void sigio_handler(int signal)
{
struct pollfd pfd;
pfd.fd = host_fd;
pfd.events = POLLIN;
poll(&pfd, 1, 0);
// if host is not connected, just exit
if (pfd.revents & POLLHUP)
return;
// host is connected so check it in main loop
check_host_connection = 1;
initial_connection = 1;
}
//dump stack trace on segfault
static void segv_handler(int signum)
{
int count;
void *syms[100];
int fd = open("/var/log/guest_agent_backtrace.log", O_RDWR|O_APPEND|O_CREAT, S_IRWXU);
if (fd == -1) {
PRINT_ERR("Unable to open guest agent backtrace file: %m");
goto out;
}
write(fd, "\n", 1);
count = backtrace(syms, 100);
if (count == 0) {
char *log = "Got zero items in backtrace.\n";
write(fd, log, strlen(log));
goto out;
}
backtrace_symbols_fd(syms, count, fd);
out:
fflush(NULL);
exit(-1);
}
int main(int argc, char **argv)
{
int flags;
int rc;
struct sockaddr_un svaddr;
int addrlen;
PRINT_INFO("%s starting up\n", *argv);
// optional arg for log level. Higher number means more logs
if (argc > 1) {
char *endptr, *str;
long val;
str = argv[1];
errno = 0;
val = strtol(str, &endptr, 0);
if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
|| (errno != 0 && val == 0)) {
PRINT_ERR("error parsing log level arg: strtol: %m");
exit(-1);
}
if (endptr == str) {
PRINT_ERR("No digits were found\n");
exit(EXIT_FAILURE);
}
if (val > LOG_DEBUG)
val = LOG_DEBUG;
setlogmask(LOG_UPTO(val));
} else
setlogmask(LOG_UPTO(LOG_WARNING));
signal(SIGIO, sigio_handler);
signal(SIGSEGV, segv_handler);
// set up fd for talking to host
host_fd = open("/dev/virtio-ports/cgcs.messaging", O_RDWR|O_NONBLOCK);
if (host_fd == -1) {
PRINT_ERR("problem with open: %m");
exit(-1);
}
flags = fcntl(host_fd, F_GETFL);
rc = fcntl(host_fd, F_SETFL, flags | O_ASYNC);
if (rc == -1) {
PRINT_ERR("problem setting host_fd async: %m");
exit(-1);
}
rc = fcntl(host_fd, F_SETOWN, getpid());
if (rc == -1) {
PRINT_ERR("problem owning host_fd: %m");
exit(-1);
}
// set up socket for talking to apps
app_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (app_fd == -1) {
PRINT_ERR("problem with socket: %m");
exit(-1);
}
flags = fcntl(app_fd, F_GETFL, 0);
fcntl(app_fd, F_SETFL, flags | O_NONBLOCK);
memset(&svaddr, 0, sizeof(struct sockaddr_un));
svaddr.sun_family = AF_UNIX;
svaddr.sun_path[0] = '\0';
strncpy(svaddr.sun_path+1, AGENT_ADDR, sizeof(svaddr.sun_path) - 2);
addrlen = sizeof(sa_family_t) + strlen(AGENT_ADDR) + 1;
if (bind(app_fd, (struct sockaddr *) &svaddr, addrlen) == -1) {
PRINT_ERR("problem with bind: %m");
exit(-1);
}
tok = json_tokener_new();
while(1) {
struct pollfd pollfds[MAX_FDS_GUEST];
int i;
int nfds = 0;
if (check_host_connection) {
// we think the host connection is up
if (initial_connection) {
//mask SIGIO if we haven't already
mask_sigio();
initial_connection=0;
}
pollfds[nfds].fd = host_fd;
pollfds[nfds].events = POLLIN;
nfds++;
}
pollfds[nfds].fd = app_fd;
pollfds[nfds].events = POLLIN;
nfds++;
if (nfds > 0) {
rc = poll(pollfds, nfds, -1);
if (rc == -1) {
if (errno == EINTR)
continue;
PRINT_ERR("problem with poll: %m");
free(tok);
exit(-1);
}
for(i=0;i<nfds;i++) {
if (pollfds[i].fd == host_fd)
scan_host_fd(pollfds+i);
if (pollfds[i].fd == app_fd)
scan_app_fd(pollfds+i);
}
} else
// no connected fds, just wait for SIGIO
pause();
}
free(tok);
return 0;
}

View File

@ -1,95 +0,0 @@
/*
* Copyright (c) 2013-2016, Wind River Systems, Inc.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3) Neither the name of Wind River Systems nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef GUESTHOST_MSG_H
#define GUESTHOST_MSG_H
/* This implements a library for generic guest-host messaging.
*
* This handles some of the boilerplate code that would be common to
* all applications using the generic guest/host communications. That way
* any changes can be made in a single place.
*
* This should be threadsafe as long as multiple threads don't try to
* simultaneously process incoming messages using the same gh_info_t pointer.
*
*/
#include <sys/un.h>
#include <json-c/json.h>
/* Function signature for the guest-host messaging callback function.
* source_addr is a null-terminated string representing the host source address.
* The message contents are up to the sender of the message.
*/
typedef void (*gh_msg_handler_t)(const char *source_addr, struct json_object *jobj_msg);
#define GH_ERRORSIZE 400
typedef struct {
int sock; // socket for talking to guest agent
struct sockaddr_un svaddr; // address of guest agent
int svaddrlen; // length of guest agent address
char errorbuf[GH_ERRORSIZE];
gh_msg_handler_t gh_msg_handler;
} gh_info_t;
/* Allocate socket, set up callbacks, etc. This must be called once before
* any other API calls. "addr" is a null-terminated string of 16 chars or less
* (including the null) that is unique within this guest. "info" is the address
* of a value-result pointer that will be updated during the call.
*
* On success returns a socket and "info" is updated to point to an allocated chunk of memory.
* On error will return -1. If it was unable to allocate memory then "info" will be
* NULL. If it was able to allocate memory but something else failed then "info" will
* be non-NULL and you can call gh_get_error() to get an error message.
*/
int gh_init(gh_msg_handler_t msg_handler, char *addr, gh_info_t **info);
/* This should be called when the socket becomes readable. This may result in
* callbacks being called. Returns 0 on success.
* A negative return value indicates an error of some kind.
*/
int gh_process_msg(gh_info_t *info);
/* Send a message to an address on the host.
* Returns 0 on success.
* A negative return value indicates an error of some kind.
* The message must be a null-terminated string without embedded newlines.
*/
int gh_send_msg(gh_info_t *info, const char *dest_addr, const char *msg);
/* Get error message from most recent library call that returned an error. */
char *gh_get_error(gh_info_t *info);
#endif

View File

@ -1,461 +0,0 @@
/*
* Copyright (c) 2013-2016, Wind River Systems, Inc.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3) Neither the name of Wind River Systems nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
This is a backchannel messaging agent that will run on the host in order to
pass messages between the host and the guest.
When a new instance appears (detected by a new unix socket of the specified
format being added to the watched directory) we open a unix stream socket
and connect to the instance, storing the mapping from instance to socket.
When an instance dies we will close the socket and remove the mapping.
We will monitor the connections to the instances as well as a unix datagram
socket used to communicate with other apps on the host. Messages coming
from an instance will be forwarded to the appropriate app, and vice versa.
If we try to send a message to a guest socket that has nothing listening
within the guest, by default the message will get queued up without giving
us any indication that there is no listener. These messages can get bundled
together when they get delivered to the guest.
*/
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <linux/un.h>
#include <fcntl.h>
#include <string.h>
#include <stddef.h>
#include <sys/time.h>
#include <signal.h>
#include <unistd.h>
#include <poll.h>
#include <limits.h>
#include <syslog.h>
#include <execinfo.h>
#include <json-c/json.h>
#include "misc.h"
#include "host_guest_msg_type.h"
#include "host_instance_mgmt.h"
int app_fd;
// One tokener for each instance connection serve as reassembly buffer
struct json_tokener* tok[MAX_FDS_HOST];
#define SERVER_SOCKET_FORMAT \
"/var/lib/libvirt/qemu/cgcs.messaging.%s.sock"
// Message has arrived from the guest.
// This assumes the message has been validated
void process_msg(json_object *jobj_msg, int fd)
{
int rc;
struct sockaddr_un cliaddr;
char *name;
int addrlen;
name = instance_name_by_fd(fd);
if (!name) {
PRINT_ERR("whoops, can't get instance name from fd, dropping\n");
return;
}
// parse version
struct json_object *jobj_version;
if (!json_object_object_get_ex(jobj_msg, VERSION, &jobj_version)) {
PRINT_ERR("failed to parse version\n");
return;
}
int version = json_object_get_int(jobj_version);
if (version != CUR_VERSION) {
PRINT_ERR("received version %d, expected %d\n", version, CUR_VERSION);
return;
}
// parse source addr
struct json_object *jobj_source_addr;
if (!json_object_object_get_ex(jobj_msg, SOURCE_ADDR, &jobj_source_addr)) {
PRINT_ERR("failed to parse source_addr\n");
return;
}
// parse dest addr
struct json_object *jobj_dest_addr;
if (!json_object_object_get_ex(jobj_msg, DEST_ADDR, &jobj_dest_addr)) {
PRINT_ERR("failed to parse dest_addr\n");
return;
}
const char *dest_addr = json_object_get_string(jobj_dest_addr);
// parse data. data is a json object that is nested inside the msg
struct json_object *jobj_data;
if (!json_object_object_get_ex(jobj_msg, DATA, &jobj_data)) {
PRINT_ERR("failed to parse data\n");
return;
}
//create outgoing message
struct json_object *jobj_outmsg = json_object_new_object();
if (jobj_outmsg == NULL) {
PRINT_ERR("failed to allocate json object for jobj_outmsg\n");
return;
}
json_object_object_add(jobj_outmsg, DATA, jobj_data);
json_object_object_add(jobj_outmsg, VERSION, json_object_new_int(CUR_VERSION));
json_object_object_add(jobj_outmsg, SOURCE_ADDR, jobj_source_addr);
json_object_object_add(jobj_outmsg, SOURCE_INSTANCE, json_object_new_string(name));
const char *outmsg = json_object_to_json_string_ext(jobj_outmsg, JSON_C_TO_STRING_PLAIN);
ssize_t outlen = strlen(outmsg);
// Set up destination address
memset(&cliaddr, 0, sizeof(struct sockaddr_un));
cliaddr.sun_family = AF_UNIX;
cliaddr.sun_path[0] = '\0';
strncpy(cliaddr.sun_path+1, dest_addr, strlen(dest_addr));
addrlen = sizeof(sa_family_t) + strlen(dest_addr) + 1;
// Send the message to the client.
// This will get transparently restarted if interrupted by signal.
rc = sendto(app_fd, outmsg, outlen, 0, (struct sockaddr *) &cliaddr,
addrlen);
if (rc == -1) {
PRINT_ERR("unable to send msg to client %.*s: %m\n", UNIX_ADDR_LEN,
cliaddr.sun_path+1);
} else if (rc != outlen) {
PRINT_ERR("sendto didn't send the whole message to client\n");
}
json_object_put(jobj_outmsg);
}
// Read and process all messages from the guest. If the guest dies, tear
// down the connection.
void scan_guest_fd(struct pollfd *pfd)
{
char buf[10000];
ssize_t rc;
if (pfd->revents & POLLHUP) {
// The only known cause of this is the death of the qemu process.
// Tear everything down.
disconnect_guest(pfd->fd);
} else if (pfd->revents & POLLIN) {
// Read a message from the guest socket.
// We assume that all the data arrives in one packet.
// To handle arbitrary messages sizes we should receive into a buffer
// with knowledge of message length, etc. Can extend later if needed.
rc = read(pfd->fd, buf, sizeof(buf));
if (rc == 0) {
PRINT_INFO("got read of 0 bytes on guest fd\n");
return;
} else if (rc < 0) {
if (errno == EAGAIN)
// Odd, should have been a message
return;
else {
PRINT_ERR("read from guest: %m");
return;
}
}
handle_virtio_serial_msg(buf, rc, pfd->fd, tok[pfd->fd]);
}
}
// validate header and send message to specified guest
void handle_app_msg(const char *msg, struct sockaddr_un *cliaddr,
socklen_t cliaddrlen)
{
int rc;
char *app_addr;
int sock;
//parse incoming msg
struct json_object *jobj_msg = json_tokener_parse(msg);
if (jobj_msg == NULL) {
PRINT_ERR("failed to parse msg\n");
return;
}
// parse version
struct json_object *jobj_version;
int version;
if (!json_object_object_get_ex(jobj_msg, VERSION, &jobj_version)) {
PRINT_ERR("failed to parse version\n");
goto done;
}
version = json_object_get_int(jobj_version);
if (version != CUR_VERSION) {
PRINT_ERR("message from app version %d, expected %d, dropping\n",
version, CUR_VERSION);
goto done;
}
// parse dest addr
struct json_object *jobj_dest_addr;
if (!json_object_object_get_ex(jobj_msg, DEST_ADDR, &jobj_dest_addr)) {
PRINT_ERR("failed to parse dest_address\n");
goto done;
}
// parse dest instance
struct json_object *jobj_dest_instance;
if (!json_object_object_get_ex(jobj_msg, DEST_INSTANCE, &jobj_dest_instance)) {
PRINT_ERR("failed to parse dest_instance\n");
goto done;
}
const char *dest_instance = json_object_get_string(jobj_dest_instance);
// parse data
struct json_object *jobj_data;
if (!json_object_object_get_ex(jobj_msg, DATA, &jobj_data)) {
PRINT_ERR("failed to parse data\n");
goto done;
}
if (cliaddr->sun_path[0] == '\0') {
app_addr = cliaddr->sun_path+1;
// get length without family or leading null from abstract namespace
cliaddrlen = cliaddrlen - sizeof(sa_family_t) - 1;
app_addr[cliaddrlen] = '\0';
} else {
PRINT_INFO("client address not in abstract namespace, dropping\n");
goto done;
}
// look up the guest socket based on the instance name
sock = fd_find_by_instance_name((char *)dest_instance);
if (sock == -1) {
PRINT_INFO("unable to find instance connection socket for %.20s\n",
dest_instance);
goto done;
}
struct json_object *jobj_outmsg = json_object_new_object();
if (jobj_outmsg == NULL) {
PRINT_ERR("failed to allocate json object for outmsg\n");
goto done;
}
json_object_object_add(jobj_outmsg, DATA, jobj_data);
json_object_object_add(jobj_outmsg, VERSION, jobj_version);
json_object_object_add(jobj_outmsg, DEST_ADDR, jobj_dest_addr);
json_object_object_add(jobj_outmsg, SOURCE_ADDR, json_object_new_string(app_addr));
const char *outmsg = json_object_to_json_string_ext(jobj_outmsg, JSON_C_TO_STRING_PLAIN);
// send to guest
ssize_t outlen = strlen(outmsg);
rc = send(sock, outmsg, outlen, 0);
if (rc == -1) {
PRINT_ERR("unable to send msg from %.*s: %m\n", UNIX_ADDR_LEN, app_addr);
} else if (rc != outlen) {
PRINT_ERR("write didn't write the whole message\n");
}
// use '\n' to delimit JSON string
rc = send(sock, "\n", 1, 0);
if (rc == -1) {
PRINT_ERR("unable to send \\n \n");
}
json_object_put(jobj_outmsg);
done:
json_object_put(jobj_msg);
}
// Read and process a message from the application socket
void scan_app_fd()
{
char buf[10000];
struct sockaddr_un cliaddr;
ssize_t rc;
// Process a message from the app socket
socklen_t addrlen = sizeof(struct sockaddr_un);
rc = recvfrom(app_fd, buf, sizeof(buf), 0,
(struct sockaddr *) &cliaddr, &addrlen);
if (rc < 0) {
if (errno == EAGAIN)
// Odd, should have been a message
return;
else {
PRINT_ERR("error in recvfrom from app: %m");
return;
}
}
handle_app_msg(buf, &cliaddr, addrlen);
}
//dump stack trace on segfault
static void segv_handler(int signum)
{
int count;
void *syms[100];
int fd = open("/var/log/host_agent_backtrace.log", O_RDWR|O_APPEND|O_CREAT, S_IRWXU);
if (fd == -1) {
PRINT_ERR("Unable to open host agent backtrace file: %m");
goto out;
}
write(fd, "\n", 1);
count = backtrace(syms, 100);
if (count == 0) {
char *log = "Got zero items in backtrace.\n";
write(fd, log, strlen(log));
goto out;
}
backtrace_symbols_fd(syms, count, fd);
out:
fflush(NULL);
exit(-1);
}
void free_tok()
{
int i;
for (i=0; i<MAX_FDS_HOST; i++) {
free(tok[i]);
}
}
int main(int argc, char **argv)
{
struct sockaddr_un svaddr;
int rc;
int flags;
int addrlen;
PRINT_INFO("%s starting up\n", *argv);
// optional arg for log level. Higher number means more logs
if (argc > 1) {
char *endptr, *str;
long val;
str = argv[1];
errno = 0;
val = strtol(str, &endptr, 0);
if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
|| (errno != 0 && val == 0)) {
PRINT_ERR("error parsing log level arg: strtol: %m");
exit(-1);
}
if (endptr == str) {
PRINT_ERR("No digits were found\n");
exit(EXIT_FAILURE);
}
if (val > LOG_DEBUG)
val = LOG_DEBUG;
setlogmask(LOG_UPTO(val));
} else
setlogmask(LOG_UPTO(LOG_WARNING));
signal(SIGSEGV, segv_handler);
// set up socket for talking to apps
app_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (app_fd == -1) {
PRINT_ERR("problem with socket: %m");
exit(-1);
}
flags = fcntl(app_fd, F_GETFL, 0);
fcntl(app_fd, F_SETFL, flags | O_NONBLOCK);
memset(&svaddr, 0, sizeof(struct sockaddr_un));
svaddr.sun_family = AF_UNIX;
svaddr.sun_path[0] = '\0';
strncpy(svaddr.sun_path+1, AGENT_ADDR, sizeof(svaddr.sun_path) - 2);
addrlen = sizeof(sa_family_t) + strlen(AGENT_ADDR) + 1;
if (bind(app_fd, (struct sockaddr *) &svaddr, addrlen) == -1) {
PRINT_ERR("problem with bind to agent addr: %m");
exit(-1);
}
pollfd_add(app_fd, POLLIN);
// This will set up monitoring for new/deleted instances
// and will set up connections for existing instances.
if (server_scan_init() < 0)
return -1;
int i;
for (i=0; i<MAX_FDS_HOST; i++) {
tok[i] = json_tokener_new();
}
while(1) {
int i;
// The timeout is for processing delayed connection retries.
rc = poll(pollfds, nfds, next_connection_retry_interval());
if (rc == -1) {
if (errno == EINTR)
continue;
PRINT_ERR("problem with poll: %m");
free_tok();
exit(-1);
}
// With poll() we can't tell if we timed out without actually checking
// the time, so run this unconditionally.
process_connection_retries();
for(i=0;i<nfds;i++) {
if ((pollfds[i].fd == app_fd) && (pollfds[i].revents & POLLIN))
scan_app_fd();
else if ((pollfds[i].fd == inotify_fd) && (pollfds[i].revents & POLLIN))
handle_inotify_event();
else
scan_guest_fd(pollfds+i);
}
}
free_tok();
return 0;
}

View File

@ -1,124 +0,0 @@
/*
* Copyright (c) 2013-2016, Wind River Systems, Inc.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3) Neither the name of Wind River Systems nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
*/
#define _GNU_SOURCE /* for memmem() */
#include <stddef.h>
#include <errno.h>
#include <error.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/select.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <json-c/json.h>
#include "host_guest_msg_type.h"
/*
Multiple messages from the host can be bundled together into a single "read"
so we need to check message boundaries and handle breaking the message apart.
Assume a valid message does not contain newline '\n', and newline is added to
the beginning and end of each message by the sender to delimit the boundaries.
*/
void parser(void *buf, ssize_t len, int fd, json_tokener* tok, int newline_found)
{
json_object *jobj = json_tokener_parse_ex(tok, buf, len);
enum json_tokener_error jerr = json_tokener_get_error(tok);
if (jerr == json_tokener_success) {
process_msg(jobj, fd);
json_object_put(jobj);
return;
}
else if (jerr == json_tokener_continue) {
// partial JSON is parsed , continue to read from socket.
if (newline_found) {
// if newline was found in the middle of the buffer, the message
// should be completed at this point. Throw out incomplete message
// by resetting tokener.
json_tokener_reset(tok);
}
}
else
{
// parsing error
json_tokener_reset(tok);
}
}
void handle_virtio_serial_msg(void *buf, ssize_t len, int fd, json_tokener* tok)
{
void *newline;
ssize_t len_head;
next:
if (len == 0)
return;
// search for newline as delimiter
newline = memchr(buf, '\n', len);
if (newline) {
// split buffer to head and tail at the location of newline.
// feed the head to the parser and recursively process the tail.
len_head = newline-buf;
// parse head
if (len_head > 0)
parser(buf, len_head, fd, tok, 1);
// start of the tail: skip newline
buf += len_head+1;
// length of the tail: deduct 1 for the newline character
len -= len_head+1;
// continue to process the tail.
goto next;
}
else {
parser(buf, len, fd, tok, 0);
}
}

View File

@ -1,96 +0,0 @@
/*
* Copyright (c) 2013-2016, Wind River Systems, Inc.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3) Neither the name of Wind River Systems nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef HOSTGUEST_MSG_H
#define HOSTGUEST_MSG_H
/* This implements a library for generic guest-host messaging.
*
* This handles some of the boilerplate code that would be common to
* all applications using the generic guest/host communications. That way
* any changes can be made in a single place.
*
* This should be threadsafe as long as multiple threads don't try to
* simultaneously process incoming messages using the same gh_info_t pointer.
*
*/
#include <sys/un.h>
#include <json-c/json.h>
/* Function signature for the guest-host messaging callback function.
* source_addr is a null-terminated string representing the host source address.
* The message contents are entirely up to the sender of the message.
*/
typedef void (*hg_msg_handler_t)(const char *source_addr, const char *source_instance,
struct json_object *jobj_msg);
#define HG_ERRORSIZE 400
typedef struct {
int sock; // socket for talking to guest agent
struct sockaddr_un svaddr; // address of guest agent
int svaddrlen; // length of guest agent address
char errorbuf[HG_ERRORSIZE];
hg_msg_handler_t hg_msg_handler;
} hg_info_t;
/* Allocate socket, set up callbacks, etc. This must be called once before
* any other API calls. "addr" is a null-terminated string of 16 chars or less
* (including the null) that is unique within this guest. "info" is the address
* of a value-result pointer that will be updated during the call.
*
* On success returns a socket and "info" is updated to point to an allocated chunk of memory.
* On error will return -1. If it was unable to allocate memory then "info" will be
* NULL. If it was able to allocate memory but something else failed then "info" will
* be non-NULL and you can call hg_get_error() to get an error message.
*/
int hg_init(hg_msg_handler_t msg_handler, char *addr, hg_info_t **info);
/* This should be called when the socket becomes readable. This may result in
* callbacks being called. Returns 0 on success.
* A negative return value indicates an error of some kind.
*/
int hg_process_msg(hg_info_t *info);
/* Send a message to an address on the host.
* Returns 0 on success.
* A negative return value indicates an error of some kind.
* The message must be a null-terminated string without embedded newlines.
*/
int hg_send_msg(hg_info_t *info, const char *dest_addr, const char *dest_instance,
const char *msg);
/* Get error message from most recent library call that returned an error. */
char *hg_get_error(hg_info_t *info);
#endif

View File

@ -1,75 +0,0 @@
/*
* Copyright (c) 2013-2016, Wind River Systems, Inc.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3) Neither the name of Wind River Systems nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef HOST_GUEST_MSG_TYPE_H
#define HOST_GUEST_MSG_TYPE_H
#include <stdint.h>
#include <json-c/json.h>
#include "misc.h"
#define CUR_VERSION 2
// The server group message is JSON encoded null-terminated string without
// embedded newlines.
// keys for messages:
#define VERSION "version"
#define SOURCE_ADDR "source_addr"
#define DEST_ADDR "dest_addr"
#define SOURCE_INSTANCE "source_instance"
#define DEST_INSTANCE "dest_instance"
#define DATA "data"
// Used by the message reassembly code.
// The underlying implementation uses page-size buffers
#define HOST_GUEST_BUFSIZE 4096
#define MAX_INSTANCES 100
#define MAX_FDS_HOST (MAX_INSTANCES+10)
#define INSTANCE_NAME_SIZE 20
// unix socket abstract namespace address of both host and guest agent
#define AGENT_ADDR "cgcs.messaging"
#define UNIX_ADDR_LEN 16
// Initialize connection message reassembly buffer
void init_msgbuf(int fd);
/* Used to store partial host_guest messages */
typedef struct {
unsigned short len;
char buf[HOST_GUEST_BUFSIZE];
} msgbuf_t;
void handle_virtio_serial_msg(void *buf, ssize_t len, int fd, json_tokener* tok);
void process_msg(json_object *jobj_msg, int fd);
#endif

View File

@ -1,629 +0,0 @@
/*
* Copyright (c) 2013-2016, Wind River Systems, Inc.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3) Neither the name of Wind River Systems nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
*/
#include <dirent.h>
#include <errno.h>
#include <execinfo.h>
#include <fcntl.h>
#include <limits.h>
#include <netdb.h>
#include <poll.h>
#include <pthread.h>
#include <resolv.h>
#include <sched.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/inotify.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/wait.h>
#include "misc.h"
#include "host_instance_mgmt.h"
/* When a new instance starts up it will create a named unix socket in a known
directory with a known filename format.
We will monitor the directory using inotify. On detection of a new instance we
will add the instance to our list of instances, create a socket, and connect it
to the named socket. On detection of a deleted instance we will tear it all
down.
We need to be able to map from socket to instance name and vice versa.
*/
// Main poll structure management stuff
struct pollfd pollfds[MAX_INSTANCES];
int nfds;
int inotify_fd;
static int inotify_watch_id;
static struct inotify_event *event_ptr;
static int event_size;
// Directory to watch for sockets
const char* host_virtio_dir = "/var/lib/libvirt/qemu";
// Mapping between instance name and fd for its connection
typedef struct {
int fd;
int pollfd_index;
char name[INSTANCE_NAME_SIZE];
} instance_t;
static int max_instance=-1;
static instance_t instances[MAX_INSTANCES];
// Lookup table indexed by instance connection fd.
// Assumes fd re-use otherwise the table would need to be bigger.
static instance_t *instance_ptrs[MAX_FDS_HOST];
// Linked list nodes for queue of connections to be retried.
struct conn_retry {
struct conn_retry *next;
unsigned long long next_try; // next retry time in nanoseconds
int sock;
int addrlen;
struct sockaddr_un un;
char instance_name[INSTANCE_NAME_SIZE];
char file_name[];
};
typedef struct conn_retry conn_retry_t;
// Head/tail pointers for queue of connections to be retried.
static conn_retry_t *retry_list;
static conn_retry_t *retry_list_tail;
// Look up the instance given the fd
char *instance_name_by_fd(int fd)
{
if (fd < MAX_FDS_HOST)
return instance_ptrs[fd]->name;
else
return NULL;
}
// Look up the instance given the instance name
instance_t *instance_find_by_instance_name(char *name)
{
int i;
for (i=0;i<=max_instance;i++) {
instance_t *instance = instances + i;
// Skip the entry if it has been invalidated.
if (instance->fd == -1)
continue;
if (strncmp(instance->name, name, INSTANCE_NAME_SIZE) == 0)
return instance;
}
return NULL;
}
// Look up the connection socket given the instance name
int fd_find_by_instance_name(char *name)
{
instance_t *instance = instance_find_by_instance_name(name);
if (instance)
return instance->fd;
else
return -1;
}
// Get the next available slot in the instance table.
instance_t *instance_get_entry()
{
int i;
// Use empty element in the existing array if possible.
for (i=0;i<=max_instance;i++) {
instance_t *instance = instances+i;
if (instance->fd == -1)
return instance;
}
// No empty elements, use a new one.
if (max_instance <= MAX_INSTANCES) {
max_instance++;
return instances+max_instance;
}
PRINT_ERR("unable to add fd, already at limit\n");
return NULL;
}
// Return the instance to the instance table.
void instance_put_entry(instance_t *instance)
{
int i;
instance->fd = -1;
i = (instance - instances)/sizeof(*instance);
if (i == max_instance)
max_instance--;
}
void init_pollfd(struct pollfd *pfd, int fd, short events)
{
pfd->fd = fd;
pfd->events = events;
pfd->revents = 0;
}
// Add a new file descriptor to be monitored, return the index
// in the pollfds table.
int pollfd_add(int fd, short events)
{
int i;
// Use empty element in the existing array if possible.
for (i=0;i<nfds;i++) {
if (pollfds[i].fd == -1) {
// Use this element
printf("reusing pollfd index %d\n", i);
init_pollfd(pollfds+i, fd, events);
return i;
}
}
// No empty elements, use a new one.
if (nfds < MAX_INSTANCES) {
int tmp = nfds;
nfds++;
PRINT_DEBUG("using new pollfd index %d\n", tmp);
init_pollfd(pollfds+tmp, fd, events);
return tmp;
}
PRINT_ERR("unable to add fd, already at limit\n");
return -1;
}
// Delete the specified index in the pollfds table. */
void pollfd_del_idx(int idx)
{
// Invalidate the pollfd table entry.
pollfds[idx].fd = -1;
// If we just invalidated the last entry in the array
// then decrement nfds until we get to a valid entry.
while(pollfds[nfds-1].fd == -1)
nfds--;
}
// Set up all the data structures for a new instance.
int add_instance(int fd, short events, char *name)
{
if (fd >= MAX_FDS_HOST) {
PRINT_ERR("fd too large to store");
return -1;
}
// Check if the instance is already in our list;
instance_t *ptr = instance_find_by_instance_name(name);
if (ptr) {
PRINT_INFO("instance %.20s already in table", name);
return 0;
} else {
instance_t *instance;
int idx;
if (max_instance == MAX_INSTANCES-1) {
PRINT_ERR("hit max number of instances");
return -1;
}
idx = pollfd_add(fd, events);
if (idx == -1)
return -1;
PRINT_DEBUG("adding instance %.20s at pollfd index %d\n", name, idx);
// Claim a new instance struct element.
instance = instance_get_entry();
instance->fd = fd;
instance->pollfd_index = idx;
strncpy(instance->name, name, sizeof(instance->name));
// Index the new element for easy access later.
instance_ptrs[fd] = instance;
return 0;
}
}
// The instance socket has disappeared, tear it all down.
void vio_full_disconnect(instance_t *instance)
{
close(instance->fd);
// Clear the lookup table entry.
instance_ptrs[instance->fd] = NULL;
// Clear the pollfd table entry.
pollfd_del_idx(instance->pollfd_index);
// Clear the instance table entry
instance_put_entry(instance);
}
/*
* Check a filename against the expected pattern for a cgcs messaging socket.
* If satisfied, writes to the passed-in instance_name arg;
*
* Returns a pointer to the instance name on success, or NULL on failure.
*/
char *file_to_instance_name(char *filename, char* instance_name,
unsigned int inst_name_len) {
int rc;
char format_string[100];
if (inst_name_len == 0)
return NULL;
snprintf(format_string, sizeof(format_string),
"cgcs.messaging.%%%d[^.].sock", inst_name_len-1);
rc = sscanf(filename, format_string, instance_name);
if (rc == 1)
return instance_name;
else
return NULL;
}
// poll() has told us the socket has been disconnected
void disconnect_guest(int fd)
{
instance_t *instance = instance_ptrs[fd];
// Sanity check
if (instance->fd != fd)
return;
PRINT_INFO("Detected disconnect of instance '%.20s'\n", instance->name);
vio_full_disconnect(instance);
}
// Inotify has told us that a file has been deleted.
static void socket_deleted(char *fn)
{
char buf[INSTANCE_NAME_SIZE];
char* instance_name;
instance_t * instance;
if (!fn)
return;
instance_name = file_to_instance_name(fn, buf, sizeof(buf));
if (!instance_name)
// Not a file we care about.
return;
instance = instance_find_by_instance_name(instance_name);
if (!instance) {
PRINT_ERR("Couldn't find record for instance %.20s\n", instance_name);
return;
}
PRINT_INFO("Detected deletion of vio file '%s'\n", fn);
vio_full_disconnect(instance);
}
// Get time in nanoseconds
static unsigned long long gettime()
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (unsigned long long)ts.tv_sec * 1000000000ULL + ts.tv_nsec;
}
// Time till next connection retry in milliseconds, for use as poll() timeout.
int next_connection_retry_interval()
{
unsigned long long time_ns;
if (!retry_list)
return -1; // infinite timeout
time_ns = gettime();
if (time_ns > retry_list->next_try)
return 0; // immediate timeout
else
return (retry_list->next_try - time_ns)/1000000; // calculated timeout
}
// We always enqueue at the list tail
static void enqueue_retry(conn_retry_t *retry)
{
if (retry_list_tail)
retry_list_tail->next = retry;
else
retry_list = retry;
retry_list_tail = retry;
retry->next = NULL;
}
// We always dequeue from the list head
static conn_retry_t *dequeue_retry()
{
conn_retry_t *tmp = retry_list;
if (retry_list)
retry_list = retry_list->next;
if (!retry_list)
retry_list_tail = NULL;
return tmp;
}
// The initial connection attempt failed, add the socket to the connection
// retry list.
static void queue_connection_retry(int sock, char *filename,
char *instance_name, struct sockaddr_un *un, int addrlen)
{
PRINT_DEBUG("attempting to queue '%s' for connection retry\n", filename);
conn_retry_t *retry = malloc(sizeof(*retry) + strlen(filename) + 1);
if (!retry) {
PRINT_ERR("unable to allocate memory for connection retry\n");
return;
}
retry->sock = sock;
strncpy(retry->instance_name, instance_name, sizeof(retry->instance_name));
strcpy(retry->file_name, filename);
retry->next_try = gettime() + 1000000000ULL; // delay for one second
memcpy(&retry->un, un, sizeof(retry->un));
retry->addrlen = addrlen;
enqueue_retry(retry);
}
// We've detected a new socket corresponding to a VM. Try and open
// a connection to it.
static int socket_added(char *filename)
{
int rc;
int addrlen;
int sock;
struct sockaddr_un un;
char pathname[PATH_MAX];
char *instance_name;
char namebuf[INSTANCE_NAME_SIZE];
instance_t * instance;
int flags;
if (!filename) {
PRINT_ERR("socket_added called with null filename\n");
return -1;
}
instance_name = file_to_instance_name(filename, namebuf, sizeof(namebuf));
if (!instance_name) {
// Not a bug, just not a file we care about.
return -1;
}
instance = instance_find_by_instance_name(instance_name);
if (instance) {
PRINT_DEBUG("'%s' is already known\n", instance_name);
return 0;
}
snprintf(pathname, sizeof(pathname), "%s/%s", host_virtio_dir, filename);
sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (sock < 0) {
PRINT_ERR("failed to get socket: %m\n");
return -1;
}
flags = fcntl(sock, F_GETFL, 0);
rc = fcntl(sock, F_SETFL, flags | O_NONBLOCK);
if (rc < 0) {
PRINT_ERR("fcntl failed: %s\n", strerror(errno));
close(sock);
return -1;
}
un.sun_family = AF_UNIX;
snprintf(pathname, sizeof(pathname), "%s/%s", host_virtio_dir, filename);
strcpy(un.sun_path, pathname);
addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(pathname);
rc = connect(sock, (struct sockaddr *)&un, addrlen);
if (rc < 0) {
if (errno == ECONNREFUSED || errno == EAGAIN) {
// temporary glitch, retry later
queue_connection_retry(sock, filename, instance_name, &un, addrlen);
return 0;
} else {
PRINT_ERR("connect to '%s' failed: %m\n", pathname);
close(sock);
return -1;
}
}
PRINT_INFO("Connection accepted to '%s'\n", pathname);
rc = add_instance(sock, POLLIN, instance_name);
if (rc < 0) {
close(sock);
return -1;
}
PRINT_INFO("added instance at '%s'\n", filename);
PRINT_INFO("registered instance sock %d\n", sock);
return 0;
}
// process any outstanding connection retries
void process_connection_retries()
{
int rc;
conn_retry_t *retry;
unsigned long long time;
while (retry_list) {
time = gettime();
if (time < retry_list->next_try)
return;
retry = dequeue_retry();
PRINT_DEBUG("dequeued '%s' for connect() retry\n", retry->file_name);
rc = connect(retry->sock, (struct sockaddr *)&retry->un,
retry->addrlen);
if (rc < 0) {
if (errno == ECONNREFUSED || errno == EAGAIN) {
// VM hasn't registered socket yet, retry later
retry->next_try = time + 1000000000ULL; //try again in a second
PRINT_DEBUG("connection for '%s' refused, enqueuing for retry\n",
retry->file_name);
enqueue_retry(retry);
continue;
} else {
PRINT_ERR("connect() for '%s' failed: %m\n", retry->file_name);
close(retry->sock);
free(retry);
continue;
}
}
PRINT_INFO("Connection accepted to '%s'\n", retry->file_name);
rc = add_instance(retry->sock, POLLIN, retry->instance_name);
if (rc < 0) {
close(retry->sock);
free(retry);
continue;
}
// Success path
PRINT_INFO("registered instance sock %d\n", retry->sock);
PRINT_DEBUG("freeing retry struct for '%s'\n", retry->un.sun_path);
free(retry);
}
}
void handle_inotify_event()
{
int len;
int bufsize = sizeof(struct inotify_event) + PATH_MAX + 1;
char buf[bufsize];
int offset = 0;
len = read(inotify_fd, buf, bufsize);
if (len < 0)
return;
// There can be multiple events returned in a single buffer, need
// to process all of them.
while (len-offset > sizeof(struct inotify_event)) {
struct inotify_event *in_event_p = (struct inotify_event *)(buf+offset);
if ((in_event_p->mask & IN_CREATE) == IN_CREATE) {
PRINT_DEBUG("inotify creation event for '%s'\n", in_event_p->name);
socket_added(in_event_p->name);
} else if ((in_event_p->mask & IN_DELETE) == IN_DELETE) {
PRINT_DEBUG("inotify deletion event for '%s'\n", in_event_p->name);
socket_deleted(in_event_p->name);
}
// Now skip to the next inotify event if there is one
offset += (sizeof(struct inotify_event) + in_event_p->len);
}
}
static void server_scan()
{
DIR *dirp;
struct dirent entry;
struct dirent *result;
int rc;
dirp = opendir(host_virtio_dir);
if (!dirp) {
PRINT_ERR("opendir %s failed: %m\n", host_virtio_dir);
return;
}
while(0 == readdir_r(dirp, &entry, &result)) {
if (!result)
break;
rc = socket_added(result->d_name);
if (rc == 0) {
PRINT_DEBUG("added '%s'\n", result->d_name);
}
}
closedir(dirp);
}
int server_scan_init()
{
event_size = sizeof(struct inotify_event) + PATH_MAX + 1;
event_ptr = malloc(event_size);
inotify_fd = inotify_init();
if (inotify_fd < 0) {
PRINT_ERR("inotify_init failed: %m\n");
return -1;
}
inotify_watch_id = inotify_add_watch(inotify_fd, host_virtio_dir, IN_CREATE | IN_DELETE);
if (inotify_watch_id < 0) {
PRINT_ERR("vio_add_watch failed: %s\n", strerror(errno));
close(inotify_fd);
inotify_fd = -1;
return -1;
}
pollfd_add(inotify_fd, POLLIN);
PRINT_INFO("registered vio inotify sock %d\n", inotify_fd);
// Do initial scan to pick up existing instance connections
server_scan();
return 0;
}

View File

@ -1,65 +0,0 @@
/*
* Copyright (c) 2013-2016, Wind River Systems, Inc.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3) Neither the name of Wind River Systems nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef HOST_INSTANCE_MGMT_H
#define HOST_INSTANCE_MGMT_H
#include "host_guest_msg_type.h"
// Main poll structure management stuff
extern int nfds;
extern struct pollfd pollfds[MAX_INSTANCES];
int pollfd_add(int fd, short events);
// Used to scan for added/deleted instances
extern int inotify_fd;
// Server connection added/deleted
void handle_inotify_event();
// Set up inotify-based monitoring
int server_scan_init(void);
// Map from connection fd to instance name
char *instance_name_by_fd(int fd);
// Map from instance name to connection fd
int fd_find_by_instance_name(char *name);
// Handle disconnection of guest
void disconnect_guest(int fd);
// Handle connection retries
void process_connection_retries();
// Time till next connection retry in milliseconds.
int next_connection_retry_interval();
#endif

View File

@ -1,4 +0,0 @@
# Ignore everything in this directory
*
# Except this file
!.gitignore

View File

@ -1,239 +0,0 @@
/*
* Copyright (c) 2013-2016, Wind River Systems, Inc.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3) Neither the name of Wind River Systems nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* This implements a library to be used for guest/host clients to interface with
* non-standard functionality on the host/guest using the backchannel
* communications pathway. (The same library can be used for both directions.)
*
* The general idea is that everything that goes through this is multiplexed
* over a single unix socket so that the guest app only needs to monitor one
* socket for activity.
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/un.h>
#include <errno.h>
#include <stdlib.h>
#include <json-c/json.h>
#include "guest_host_msg.h"
#include "host_guest_msg_type.h"
/* Send a message to an address on the host.
* Returns 0 on success.
* A negative return value indicates an error of some kind.
*/
int gh_send_msg(gh_info_t *info, const char *dest_addr, const char *msg)
{
int rc;
//parse msg data
struct json_object *jobj_data = json_tokener_parse(msg);
if (jobj_data == NULL) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "failed to parse msg");
return -1;
}
struct json_object *jobj_outmsg = json_object_new_object();
if (jobj_outmsg == NULL) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "failed to allocate json object for outmsg");
json_object_put(jobj_data);
return -1;
}
json_object_object_add(jobj_outmsg, DATA, jobj_data);
json_object_object_add(jobj_outmsg, VERSION, json_object_new_int(CUR_VERSION));
json_object_object_add(jobj_outmsg, DEST_ADDR, json_object_new_string(dest_addr));
const char *outmsg = json_object_to_json_string_ext(jobj_outmsg, JSON_C_TO_STRING_PLAIN);
int msglen = strlen(outmsg);
rc = sendto(info->sock, outmsg, msglen, 0, (struct sockaddr *) &info->svaddr,
info->svaddrlen);
if (rc != msglen) {
if (rc > 0) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "sendto returned %d, expected %d",
rc, msglen);
} else
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "sendto: %m");
goto failed;
}
json_object_put(jobj_outmsg);
return 0;
failed:
json_object_put(jobj_outmsg);
return -1;
}
/* Read a message from the socket and process it. */
int gh_process_msg(gh_info_t *info)
{
char buf[HOST_GUEST_BUFSIZE];
int len;
len = recv(info->sock, buf, sizeof(buf), 0);
if (len == -1) {
if (errno == EAGAIN)
return 0;
else {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "error receiving msg: %m");
return -1;
}
}
struct json_object *jobj_msg = json_tokener_parse(buf);
if (jobj_msg == NULL) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "failed to parse msg");
return -1;
}
// parse version
struct json_object *jobj_version;
if (!json_object_object_get_ex(jobj_msg, VERSION, &jobj_version)) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "failed to parse version");
goto failed;
}
int version = json_object_get_int(jobj_version);
if (version != CUR_VERSION) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1,
"invalid version %d, expecting %d", version, CUR_VERSION);
goto failed;
}
// parse source address
struct json_object *jobj_source_addr;
if (!json_object_object_get_ex(jobj_msg, SOURCE_ADDR, &jobj_source_addr)) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "failed to parse source_addr");
goto failed;
}
const char *source_addr = json_object_get_string(jobj_source_addr);
// parse data. data is a json object that is nested inside the msg
struct json_object *jobj_data;
if (!json_object_object_get_ex(jobj_msg, DATA, &jobj_data)) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "failed to parse data");
goto failed;
}
if (info->gh_msg_handler)
info->gh_msg_handler(source_addr, jobj_data);
json_object_put(jobj_msg);
return 0;
failed:
json_object_put(jobj_msg);
return -1;
}
/* Allocate socket, set up callbacks, etc. This must be called once before
* any other API calls. "addr" is a null-terminated string of 16 chars or less
* (including the null) that is unique within this guest. "info" is the address
* of a value-result pointer that will be updated during the call.
*
* On success returns a socket and "info" is updated to point to an allocated chunk of memory.
* On error will return -1. If it was unable to allocate memory then "info" will be
* NULL. If it was able to allocate memory but something else failed then "info" will
* be non-NULL and you can call gh_get_error() to get an error message.
*/
int gh_init(gh_msg_handler_t msg_handler, char *addr, gh_info_t **in_info)
{
int flags;
int addrlen;
struct sockaddr_un cliaddr;
gh_info_t *info;
*in_info = malloc(sizeof(**in_info));
if (!*in_info)
/* unable to allocate memory */
return -1;
info = *in_info;
/* socket for talking to guest agent */
info->sock = socket(AF_UNIX, SOCK_DGRAM, 0);
if (info->sock == -1) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "unable to open socket: %m");
goto free_out;
}
flags = fcntl(info->sock, F_GETFL, 0);
fcntl(info->sock, F_SETFL, flags | O_NONBLOCK);
/* our address */
memset(&cliaddr, 0, sizeof(struct sockaddr_un));
cliaddr.sun_family = AF_UNIX;
cliaddr.sun_path[0] = '\0';
strncpy(cliaddr.sun_path+1, addr,
sizeof(cliaddr.sun_path) - 2);
addrlen = sizeof(sa_family_t) + strlen(addr) + 1;
if (bind(info->sock, (struct sockaddr *) &cliaddr, addrlen) == -1) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "unable to bind socket: %m");
goto close_out;
}
/* guest agent address */
memset(&info->svaddr, 0, sizeof(struct sockaddr_un));
info->svaddr.sun_family = AF_UNIX;
info->svaddr.sun_path[0] = '\0';
strncpy(info->svaddr.sun_path+1, AGENT_ADDR, sizeof(info->svaddr.sun_path) - 2);
info->svaddrlen = sizeof(sa_family_t) + strlen(AGENT_ADDR) + 1;
/* set up callback pointers */
info->gh_msg_handler = msg_handler;
return info->sock;
close_out:
close(info->sock);
free_out:
free(info);
return -1;
}
/* Provide access to the error message if the most recent call failed. */
char *gh_get_error(gh_info_t *info)
{
return info->errorbuf;
}

View File

@ -1,250 +0,0 @@
/*
* Copyright (c) 2013-2016, Wind River Systems, Inc.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3) Neither the name of Wind River Systems nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* This implements a library to be used for host clients to interface with
* non-standard functionality on the guest using the backchannel
* communications pathway.
*
* The general idea is that everything that goes through this is multiplexed
* over a single unix socket so that the guest app only needs to monitor one
* socket for activity.
*
* This is almost identical to lib_guest_host_msg.c but some data structures
* are different. Might be possible to extract some common stuff.
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/un.h>
#include <errno.h>
#include <stdlib.h>
#include <json-c/json.h>
#include "host_guest_msg_type.h"
#include "host_guest_msg.h"
/* Send a message to an address on the host.
* Returns 0 on success.
* A negative return value indicates an error of some kind.
*/
int hg_send_msg(hg_info_t *info, const char *dest_addr, const char *dest_instance,
const char *msg)
{
int rc;
//parse msg data
struct json_object *jobj_data = json_tokener_parse(msg);
if (jobj_data == NULL) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "failed to parse msg");
return -1;
}
struct json_object *jobj_outmsg = json_object_new_object();
if (jobj_outmsg == NULL) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "failed to allocate json object for outmsg");
json_object_put(jobj_data);
return -1;
}
json_object_object_add(jobj_outmsg, DATA, jobj_data);
json_object_object_add(jobj_outmsg, VERSION, json_object_new_int(CUR_VERSION));
json_object_object_add(jobj_outmsg, DEST_ADDR, json_object_new_string(dest_addr));
json_object_object_add(jobj_outmsg, DEST_INSTANCE, json_object_new_string(dest_instance));
const char *outmsg = json_object_to_json_string_ext(jobj_outmsg, JSON_C_TO_STRING_PLAIN);
int msglen = strlen(outmsg);
rc = sendto(info->sock, outmsg, msglen, 0, (struct sockaddr *) &info->svaddr,
info->svaddrlen);
if (rc != msglen) {
if (rc > 0) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "sendto returned %d, expected %d",
rc, msglen);
} else
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "sendto: %m");
goto failed;
}
json_object_put(jobj_outmsg);
return 0;
failed:
json_object_put(jobj_outmsg);
return -1;
}
/* Read a message from the socket and process it. */
int hg_process_msg(hg_info_t *info)
{
char buf[HOST_GUEST_BUFSIZE];
int len;
len = recv(info->sock, buf, sizeof(buf), 0);
if (len == -1) {
if (errno == EAGAIN)
return 0;
else {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "error receiving msg: %m");
return -1;
}
}
struct json_object *jobj_msg = json_tokener_parse(buf);
if (jobj_msg == NULL) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "failed to parse msg");
return -1;
}
// parse version
struct json_object *jobj_version;
if (!json_object_object_get_ex(jobj_msg, VERSION, &jobj_version)) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "failed to parse version");
goto failed;
}
int version = json_object_get_int(jobj_version);
if (version != CUR_VERSION) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "invalid version");
goto failed;
}
// parse source address
struct json_object *jobj_source_addr;
if (!json_object_object_get_ex(jobj_msg, SOURCE_ADDR, &jobj_source_addr)) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "failed to parse source_addr");
goto failed;
}
const char *source_addr = json_object_get_string(jobj_source_addr);
// parse source instance
struct json_object *jobj_source_instance;
if (!json_object_object_get_ex(jobj_msg, SOURCE_INSTANCE, &jobj_source_instance)) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "failed to parse source_instance");
goto failed;
}
const char *source_instance = json_object_get_string(jobj_source_instance);
// parse data. data is a json object that is nested inside the msg
struct json_object *jobj_data;
if (!json_object_object_get_ex(jobj_msg, DATA, &jobj_data)) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "failed to parse data");
goto failed;
}
if (info->hg_msg_handler)
info->hg_msg_handler(source_addr, source_instance, jobj_data);
json_object_put(jobj_msg);
return 0;
failed:
json_object_put(jobj_msg);
return -1;
}
/* Allocate socket, set up callbacks, etc. This must be called once before
* any other API calls. "addr" is a null-terminated string of 16 chars or less
* (including the null) that is unique within this guest. "info" is the address
* of a value-result pointer that will be updated during the call.
*
* On success returns a socket and "info" is updated to point to an allocated chunk of memory.
* On error will return -1. If it was unable to allocate memory then "info" will be
* NULL. If it was able to allocate memory but something else failed then "info" will
* be non-NULL and you can call hg_get_error() to get an error message.
*/
int hg_init(hg_msg_handler_t msg_handler, char *addr, hg_info_t **in_info)
{
int flags;
int addrlen;
struct sockaddr_un cliaddr;
hg_info_t *info;
*in_info = malloc(sizeof(**in_info));
if (!*in_info)
/* unable to allocate memory */
return -1;
info = *in_info;
/* socket for talking to guest agent */
info->sock = socket(AF_UNIX, SOCK_DGRAM, 0);
if (info->sock == -1) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "unable to open socket: %m");
goto free_out;
}
flags = fcntl(info->sock, F_GETFL, 0);
fcntl(info->sock, F_SETFL, flags | O_NONBLOCK);
/* our address */
memset(&cliaddr, 0, sizeof(struct sockaddr_un));
cliaddr.sun_family = AF_UNIX;
cliaddr.sun_path[0] = '\0';
strncpy(cliaddr.sun_path+1, addr,
sizeof(cliaddr.sun_path) - 2);
addrlen = sizeof(sa_family_t) + strlen(addr) + 1;
if (bind(info->sock, (struct sockaddr *) &cliaddr, addrlen) == -1) {
snprintf(info->errorbuf, sizeof(info->errorbuf)-1, "unable to bind socket: %m");
goto close_out;
}
/* guest agent address */
memset(&info->svaddr, 0, sizeof(struct sockaddr_un));
info->svaddr.sun_family = AF_UNIX;
info->svaddr.sun_path[0] = '\0';
strncpy(info->svaddr.sun_path+1, AGENT_ADDR, sizeof(info->svaddr.sun_path) - 2);
info->svaddrlen = sizeof(sa_family_t) + strlen(AGENT_ADDR) + 1;
/* set up callback pointers */
info->hg_msg_handler = msg_handler;
return info->sock;
close_out:
close(info->sock);
free_out:
free(info);
return -1;
}
/* Provide access to the error message if the most recent call failed. */
char *hg_get_error(hg_info_t *info)
{
return info->errorbuf;
}

View File

@ -1,42 +0,0 @@
/*
* Copyright (c) 2013-2016, Wind River Systems, Inc.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3) Neither the name of Wind River Systems nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CGCS_MSG_MISC_H
#define CGCS_MSG_MISC_H
#include <syslog.h>
#define PRINT(level, format, ...) \
syslog(level, "%s(%d): " format, __FILE__, __LINE__, ##__VA_ARGS__)
#define PRINT_ERR(format, ...) PRINT(LOG_ERR, format, ##__VA_ARGS__)
#define PRINT_INFO(format, ...) PRINT(LOG_INFO, format, ##__VA_ARGS__)
#define PRINT_DEBUG(format, ...) PRINT(LOG_DEBUG, format, ##__VA_ARGS__)
#endif

View File

@ -1,4 +0,0 @@
# Ignore everything in this directory
*
# Except this file
!.gitignore

View File

@ -1,12 +0,0 @@
[Unit]
Description=Titanium Cloud Host Guest Messaging Agent
After=cloud-init.service
[Service]
ExecStart=/usr/sbin/guest_agent
Type=simple
Restart=always
[Install]
WantedBy=multi-user.target

View File

@ -1,78 +0,0 @@
#!/bin/sh
#
# Copyright(c) 2013-2016, Wind River Systems, Inc. All rights reserved.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Wind River Systems nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
DAEMON=/usr/sbin/host_agent
NAME=host_agent
DESC="agent to communicate with guest"
ARGS=
PIDFILE=/var/run/host_agent.pid
test -f $DAEMON || exit 0
case "$1" in
start)
echo -n "starting $DESC: $NAME... "
test -d /var/lib/misc/ || mkdir /var/lib/misc/
start-stop-daemon -S -m -b -x $DAEMON --pidfile=$PIDFILE -- $ARGS
echo "done."
;;
stop)
echo -n "stopping $DESC: $NAME... "
start-stop-daemon -K -x $DAEMON --pidfile=$PIDFILE
echo "done."
;;
status)
echo -n "$NAME "
start-stop-daemon -q -K -t -x $DAEMON --pidfile=$PIDFILE
RET=$?
if [ "$RET" = "0" ]; then
PID=`cat $PIDFILE`
echo "($PID) is running"
else
echo "is not running"
# For lsb compliance return 3 if process not running
exit 3
fi
;;
restart)
echo "restarting $DESC: $NAME... "
$0 stop
$0 start
echo "done."
;;
*)
echo "Usage: $0 {start|stop|status|restart}"
exit 1
;;
esac
exit 0

View File

@ -1,24 +0,0 @@
[process]
process = host_agent
pidfile = /var/run/host_agent.pid
script = /etc/init.d/host_agent
style = lsb ; ocf or lsb
severity = major ; minor, major, critical
restarts = 3 ; restart retries before error assertion
interval = 1 ; number of seconds to wait between restarts
debounce = 20 ; number of seconds that a process needs to remain
; running before degrade is removed and retry count
; is cleared.
startuptime = 5 ; Seconds to wait after process start before starting the debounce monitor
mode = passive ; Monitoring mode: passive (default or if mode field is missing) or active
; passive: process death monitoring (default: always)
; active: heartbeat monitoring, i.e. request / response messaging
; ignore: do not monitor or stop monitoring process
subfunction = worker ; Optional label.
; Manage this process in the context of a combo host subfunction
; Choices: worker or storage.
; when specified pmond will wait for
; /var/run/.worker_config_complete or
; /var/run/.storage_config_complete
; ... before managing this process with the specified subfunction
; Excluding this label will cause this process to be managed by default on startup

View File

@ -1,13 +0,0 @@
[Unit]
Description=Titanium Cloud Host Guest Messaging Agent
After=config.service
Before=pmon.service
[Service]
Type=forking
ExecStart=/etc/init.d/host_agent start
ExecStop=/etc/init.d/host_agent stop
PIDFile=/var/run/host_agent.pid
[Install]
WantedBy=multi-user.target

View File

@ -1,497 +0,0 @@
/*
* Copyright (c) 2013-2016, Wind River Systems, Inc.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3) Neither the name of Wind River Systems nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* This implements a library to be used for guest clients to interface with
* non-standard functionality on the host using the backchannel
* communications pathway.
*
* The general idea is that everything that goes through this is multiplexed
* over a single unix socket so that the guest app only needs to monitor one
* socket for activity.
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/un.h>
#include <errno.h>
#include <stdlib.h>
#include <json-c/json.h>
#include "server_group.h"
#include "host_guest_msg_type.h"
/* unix socket abstract namespace address of guest agent */
#define GUEST_CLIENT_ADDR "cgcs.server_grp"
#define HOST_GUEST_BUFSIZE 4096 // max size of message that can be received
/* Server Group message is encoded in JSON format.
The message sent out to UNIX socket is a null-terminated JSON format string
without embedded newlines.
Format:
{key:value,key:value,..., key:value}
Key/value pairs:
"version": <integer> - version of the interface
"type": < string> - one of these types broadcast", "notification",
"status_query", "status_response",
"status_response_done”
"req": <integer> - sequence number for status_query/status_response/
status_response_done messages
"source_instance“: <string> - source instance that send out the broadcast
"data": <string> - message content for broadcast, notification,
status_query and status_response messages.
Must be a null-terminated string without embedded newlines.
Message Types:
broadcast - incoming or outgoing
notification - incoming, state change of other servers within the
server group
status_query - outgoing, query the current state of all servers
within the server group
status_response - incoming, one or more responses to the status_query
status_response_done - incoming, last response to the status query
*/
// server group message type
#define GRP_BROADCAST "broadcast" // broadcast message from another server
#define GRP_NOTIFICATION "notification" // notification of server state change
#define GRP_STATUS_QUERY "status_query" // query of status of all servers in group
#define GRP_STATUS_RESP "status_response" // query response msg (could be several)
#define GRP_STATUS_RESP_DONE "status_response_done" // query response done msg (no data)
#define GRP_NACK "nack" // nack msg indicating parse or protocol error from host
/* Header for incoming server group messages. The exact contents will differ
* depending on message type.
*
* "len" is the overall length including header.
*
* For messages with a TYPE of GRP_BROADCAST only, the "sinstance" field
* will contain the instance name of the instance that sent the broadcast, and
* DATA will contain the message that was sent.
*
*/
static int sock; // socket for talking to guest agent
static struct sockaddr_un svaddr; // address of guest agent
static int svaddrlen; // length of guest agent address
static unsigned int status_seqnum; // status query sequence number
static char *status_buf; // status query reassembly buffer
static unsigned long status_size; // current status buffer size
static unsigned long status_len; // currently used buffer length
#define ERRORSIZE 400
static char errorbuf[ERRORSIZE];
static sg_broadcast_msg_handler_t sg_broadcast_msg_callback;
static sg_notification_msg_handler_t sg_notification_msg_callback;
static sg_status_msg_handler_t sg_status_msg_callback;
/* Generic routine to send a server group message down to the host. */
int sg_send_host_msg(const char *msg_type, int seq, const char *data)
{
int rc;
struct json_object *jobj_data = json_object_new_object();
if (jobj_data == NULL) {
snprintf(errorbuf, ERRORSIZE-1, "failed to allocate json object for data");
return -1;
}
json_object_object_add(jobj_data, VERSION, json_object_new_int(CUR_VERSION));
json_object_object_add(jobj_data, MSG_TYPE, json_object_new_string(msg_type));
if (!strcmp(msg_type, GRP_STATUS_QUERY)) {
json_object_object_add(jobj_data, SEQ, json_object_new_int(seq));
}
if (data) {
json_object_object_add(jobj_data, DATA, json_object_new_string(data));
}
struct json_object *jobj_outmsg = json_object_new_object();
if (jobj_outmsg == NULL) {
snprintf(errorbuf, ERRORSIZE-1, "failed to allocate json object for outmsg");
json_object_put(jobj_data);
return -1;
}
json_object_object_add(jobj_outmsg, DATA, jobj_data);
json_object_object_add(jobj_outmsg, VERSION, json_object_new_int(CUR_VERSION));
/* This is a known address that nova-compute is listening on */
json_object_object_add(jobj_outmsg, DEST_ADDR, json_object_new_string(GUEST_CLIENT_ADDR));
const char *outmsg = json_object_to_json_string_ext(jobj_outmsg, JSON_C_TO_STRING_PLAIN);
int msglen = strlen(outmsg);
rc = sendto(sock, outmsg, msglen, 0, (struct sockaddr *) &svaddr, svaddrlen);
if (rc != msglen) {
if (rc > 0) {
snprintf(errorbuf, ERRORSIZE-1, "sendto returned %d, expected %d",
rc, msglen);
} else
snprintf(errorbuf, ERRORSIZE-1, "sendto: %m");
json_object_put(jobj_outmsg);
return -1;
}
json_object_put(jobj_outmsg);
return 0;
}
/* Send a message to all other servers in our server group. */
int sg_msg_broadcast(void *msg, unsigned int len)
{
return sg_send_host_msg(GRP_BROADCAST, 0, (const char*)msg);
}
/* Ensure the status buffer is at least as big as the specified size.
* Call realloc() if necessary to grow the buffer.
*/
int ensure_status_buf_size(unsigned int size)
{
if (size > status_size) {
/* need to grow the buffer */
void *ptr = realloc(status_buf, size);
if (!ptr) {
/* hopefully shouldn't happen */
snprintf(errorbuf, ERRORSIZE-1,
"unable to realloc buffer to size %u", size);
/* give up on current status query */
status_seqnum++;
status_len = 0;
return -1;
}
status_buf = ptr;
status_size = size;
}
return 0;
}
/* Request current status of all servers in server group. Due to limitations in
* the current implementation of host-guest comm channel agents we receive
* information on one server per response, then a final "done" message. This
* could be changed if we fix the host-guest comm channel to handle arbitrarily
* large messages.
*
* Yes, the current design is not the most robust...might want to consider adding
* an indication of how many servers we expect data for and which one we're on
* in case we lose a message or something. Better fix might be to just fix the
* host-guest comm channel to handle arbitrarily large messages.
*/
int sg_request_status()
{
int rc;
/* If we were still receiving status updates from a previous query this
* will cause them to get dropped.
*/
status_seqnum++;
status_len = 0;
/* Ensure we have room for an empty list otherwise give up.
* Start with a decent size buffer to minimize reallocs.
*/
if (ensure_status_buf_size(4096) != 0)
return -1;
rc = sg_send_host_msg(GRP_STATUS_QUERY, status_seqnum, NULL);
if (rc == 0) {
/* start a list in the buffer */
status_buf[0] = '[';
status_len = 1;
}
return rc;
}
/* Handle a response to the status query. This should contain the current
* status of a single server. We add it to the data accumulating in the buffer.
*/
int handle_status_resp(unsigned int seqnum, const char *msg, unsigned int len)
{
if (seqnum != status_seqnum) {
snprintf(errorbuf, ERRORSIZE-1,
"status resp seqnum %u doesn't match expected %u",
seqnum, status_seqnum);
return -1;
}
/* Ensure we have room for new data otherwise give up.
* Add an extra byte for comma between server data.
*/
if (ensure_status_buf_size(status_len + len + 1) != 0)
return -1;
/* comma-separate the status for each instance */
if (status_len != 1) {
status_buf[status_len] = ',';
status_len++;
}
/* Now copy the server status into the buffer */
memcpy((status_buf + status_len), msg, len);
status_len += len;
return 0;
}
/* This tells us that we've received all the server status messages
* so we can call the callback and then reset things for the next one.
*/
int handle_status_resp_done(unsigned int seqnum)
{
if (seqnum != status_seqnum) {
snprintf(errorbuf, ERRORSIZE-1,
"status resp done seqnum %u doesn't match expected %u",
seqnum, status_seqnum);
return -1;
}
/* Ensure we have room for list terminator otherwise give up */
if (ensure_status_buf_size(status_len + 1) != 0)
return -1;
if (status_buf) {
/* terminate the list */
status_buf[status_len] = ']';
status_len++;
if (sg_status_msg_callback)
sg_status_msg_callback(status_buf, status_len);
}
/* reset the buffer */
status_len = 0;
/* bump seqnum just in case */
status_seqnum++;
return 0;
}
int dispatch_sg_msg(json_object *job_msg)
{
int rc = 0;
struct json_object *jobj_msg_type;
if (!json_object_object_get_ex(job_msg, MSG_TYPE, &jobj_msg_type)) {
snprintf(errorbuf, ERRORSIZE-1, "failed to parse msg_type");
return -1;
}
const char *msg_type = json_object_get_string(jobj_msg_type);
struct json_object *jobj_data;
const char *data;
// type GRP_STATUS_RESP_DONE message does not have a data field
if (!strcmp(msg_type, GRP_BROADCAST) ||
!strcmp(msg_type, GRP_NOTIFICATION) ||
!strcmp(msg_type, GRP_STATUS_RESP)) {
if (!json_object_object_get_ex(job_msg, DATA, &jobj_data)) {
snprintf(errorbuf, ERRORSIZE-1, "failed to parse data for type %s", msg_type);
return -1;
}
data = json_object_get_string(jobj_data);
}
if (!strcmp(msg_type, GRP_BROADCAST)) {
struct json_object *jobj_source_instance;
if (!json_object_object_get_ex(job_msg, SOURCE_INSTANCE, &jobj_source_instance)) {
snprintf(errorbuf, ERRORSIZE-1, "failed to parse source_instance for type %s", msg_type);
return -1;
}
const char *source_instance = json_object_get_string(jobj_source_instance);
if (sg_broadcast_msg_callback)
sg_broadcast_msg_callback((char *)source_instance, (void *)data, strlen(data));
}
else if (!strcmp(msg_type, GRP_NOTIFICATION)) {
if (sg_notification_msg_callback)
sg_notification_msg_callback((void *)data, strlen(data));
}
else if ((!strcmp(msg_type, GRP_STATUS_RESP)) || (!strcmp(msg_type, GRP_STATUS_RESP_DONE))) {
struct json_object *jobj_seq;
if (!json_object_object_get_ex(job_msg, SEQ, &jobj_seq)) {
snprintf(errorbuf, ERRORSIZE-1, "failed to parse seq for type %s", msg_type);
return -1;
}
int seq = json_object_get_int(jobj_seq);
if (!strcmp(msg_type, GRP_STATUS_RESP)) {
rc = handle_status_resp(seq, data, strlen(data));
}
else if (!strcmp(msg_type, GRP_STATUS_RESP_DONE)) {
rc = handle_status_resp_done(seq);
}
}
else if (!strcmp(msg_type, GRP_NACK)) {
struct json_object *jobj_log_msg;
if (!json_object_object_get_ex(job_msg, LOG_MSG, &jobj_log_msg)) {
snprintf(errorbuf, ERRORSIZE-1, "Nack: failed to parse log_msg");
}
const char *log_msg = json_object_get_string(jobj_log_msg);
snprintf(errorbuf, ERRORSIZE-1, "Nack received, error message from host: %s", log_msg);
return -1;
} else {
snprintf(errorbuf, ERRORSIZE-1, "unknown server group message type %s", msg_type);
return -1;
}
return rc;
}
/* Read a message from the socket and process it. */
int process_sg_msg()
{
char buf[HOST_GUEST_BUFSIZE];
int len;
int rc = -1;
len = recv(sock, buf, sizeof(buf), 0);
if (len == -1) {
if (errno == EAGAIN)
return 0;
else {
snprintf(errorbuf, ERRORSIZE-1, "error receiving msg: %m");
return -1;
}
}
struct json_object *jobj_msg = json_tokener_parse(buf);
if (jobj_msg == NULL) {
snprintf(errorbuf, ERRORSIZE-1, "failed to parse msg");
return -1;
}
// parse version
struct json_object *jobj_version;
if (!json_object_object_get_ex(jobj_msg, VERSION, &jobj_version)) {
snprintf(errorbuf, ERRORSIZE-1, "failed to parse version");
goto done;
}
int version = json_object_get_int(jobj_version);
if (version != CUR_VERSION) {
snprintf(errorbuf, ERRORSIZE-1, "invalid version");
goto done;
}
// parse source address
struct json_object *jobj_source_addr;
if (!json_object_object_get_ex(jobj_msg, SOURCE_ADDR, &jobj_source_addr)) {
snprintf(errorbuf, ERRORSIZE-1, "failed to parse source_addr");
goto done;
}
const char *source_addr = json_object_get_string(jobj_source_addr);
/* check the host sender */
if (strcmp(source_addr, GUEST_CLIENT_ADDR) != 0) {
snprintf(errorbuf, ERRORSIZE-1, "unknown sender address %s", source_addr);
goto done;
}
// parse data. data is a json object that is nested inside the msg
struct json_object *jobj_data;
if (!json_object_object_get_ex(jobj_msg, DATA, &jobj_data)) {
snprintf(errorbuf, ERRORSIZE-1, "failed to parse data");
goto done;
}
rc = dispatch_sg_msg(jobj_data);
done:
json_object_put(jobj_msg);
return rc;
}
/* This needs to be called first to initialize sockets, buffers,
* callback pointers, etc.
*/
int init_sg(sg_broadcast_msg_handler_t broadcast_handler,
sg_notification_msg_handler_t notification_handler,
sg_status_msg_handler_t status_handler)
{
int flags;
int addrlen;
struct sockaddr_un cliaddr;
// socket for talking to guest agent
sock = socket(AF_UNIX, SOCK_DGRAM, 0);
if (sock == -1) {
snprintf(errorbuf, ERRORSIZE-1, "unable to open socket: %m");
return -1;
}
flags = fcntl(sock, F_GETFL, 0);
fcntl(sock, F_SETFL, flags | O_NONBLOCK);
/* our address */
memset(&cliaddr, 0, sizeof(struct sockaddr_un));
cliaddr.sun_family = AF_UNIX;
cliaddr.sun_path[0] = '\0';
strncpy(cliaddr.sun_path+1, GUEST_CLIENT_ADDR,
sizeof(cliaddr.sun_path) - 2);
addrlen = sizeof(sa_family_t) + strlen(GUEST_CLIENT_ADDR) + 1;
if (bind(sock, (struct sockaddr *) &cliaddr, addrlen) == -1) {
snprintf(errorbuf, ERRORSIZE-1, "unable to bind socket: %m");
return -1;
}
/* guest agent address */
memset(&svaddr, 0, sizeof(struct sockaddr_un));
svaddr.sun_family = AF_UNIX;
svaddr.sun_path[0] = '\0';
strncpy(svaddr.sun_path+1, AGENT_ADDR, sizeof(svaddr.sun_path) - 2);
svaddrlen = sizeof(sa_family_t) + strlen(AGENT_ADDR) + 1;
/* set up callback pointers */
sg_broadcast_msg_callback = broadcast_handler;
sg_notification_msg_callback = notification_handler;
sg_status_msg_callback = status_handler;
return sock;
}
/* Provide access to the error message if the most recent call failed. */
char *sg_get_error()
{
return errorbuf;
}

View File

@ -1,119 +0,0 @@
/*
* Copyright (c) 2013-2016, Wind River Systems, Inc.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3) Neither the name of Wind River Systems nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
*/
#ifndef GUEST_CLIENT_H
#define GUEST_CLIENT_H
// keys for server group messages
#define VERSION "version"
#define MSG_TYPE "msg_type"
#define SEQ "seq"
#define SOURCE_INSTANCE "source_instance"
#define DATA "data"
#define LOG_MSG "log_msg"
/* This implements a library for server group messaging.
*
* The general idea is that everything that goes through this is multiplexed
* over a single unix socket so that the guest app only needs to monitor one
* socket for activity.
*
* This has not been tested for safe use in multithreaded applications.
*/
/* Function signature for the server group broadcast messaging callback function.
* source_instance is a null-terminated string of the form "instance-xxxxxxxx".
* The message contents are entirely up to the sender of the message.
*/
typedef void (*sg_broadcast_msg_handler_t)(char *source_instance, void *msg,
unsigned short msglen);
/* Function signature for the server group notification callback function. The
* message is basically the notification as sent out by nova with some information
* removed as not relevant. The message is not null-terminated, though it is
* a JSON representation of a python dictionary.
*/
typedef void (*sg_notification_msg_handler_t)(void *msg, unsigned short msglen);
/* Function signature for the server group status callback function. The
* message is a JSON representation of a list of dictionaries, each of which
* corresponds to a single server. The message is not null-terminated.
*/
typedef void (*sg_status_msg_handler_t)(void *msg, unsigned short msglen);
/* Get error message from most recent library call that returned an error. */
char *sg_get_error();
/* Allocate socket, set up callbacks, etc. This must be called once before
* any other API calls.
*
* Returns a socket that must be monitored for activity using select/poll/etc.
* A negative return value indicates an error of some kind.
*/
int init_sg(sg_broadcast_msg_handler_t broadcast_handler,
sg_notification_msg_handler_t notification_handler,
sg_status_msg_handler_t status_handler);
/* This should be called when the socket becomes readable. This may result in
* callbacks being called. Returns 0 on success.
* A negative return value indicates an error of some kind.
*/
int process_sg_msg();
/* max msg length for a broadcast message */
#define MAX_MSG_DATA_LEN 3050
/* Send a server group broadcast message. Returns 0 on success.
* A negative return value indicates an error of some kind.
* The message must be a null-terminated string without embedded newlines.
* len is no longer used.
*/
int sg_msg_broadcast(void *msg, unsigned int len);
/* Request a status update for all servers in the group.
* Returns 0 if the request was successfully sent.
* A negative return value indicates an error of some kind.
*
* A successful response will cause the status_handler callback
* to be called.
*
* If a status update has been requested but the callback has not yet
* been called this may result in the previous request being cancelled.
*/
int sg_request_status();
#endif

View File

@ -1,107 +0,0 @@
/*
* Copyright (c) 2013-2016, Wind River Systems, Inc.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3) Neither the name of Wind River Systems nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include "server_group.h"
void sg_broadcast_msg_handler(char *source_instance, void *msg,
unsigned short msglen)
{
printf("got server group broadcast msg: len: %d, sinstance: %.20s, msg: %.*s\n\n",
msglen, source_instance, msglen, (char *)msg);
}
void sg_notification_msg_handler(void *msg, unsigned short msglen)
{
printf("got server group notification msg: %.*s\n\n",
msglen, (char *)msg);
}
void sg_status_msg_handler(void *msg, unsigned short msglen)
{
printf("got server group status response msg: %.*s\n\n",
msglen, (char *)msg);
}
int main(int argc, char **argv)
{
int nfds;
int rc;
fd_set rfds;
// socket for guest client library
int sock = init_sg(sg_broadcast_msg_handler,
sg_notification_msg_handler,
sg_status_msg_handler);
if (sock < 0) {
printf("error initializing library: %s\n", sg_get_error());
exit(-1);
}
nfds=sock+1;
FD_ZERO(&rfds);
FD_SET(sock, &rfds);
if (argc == 2) {
rc = sg_msg_broadcast(argv[1], strlen(argv[1])+1);
if (rc != 0) {
printf("problem sending broadcast: %s\n", sg_get_error());
return -1;
}
}
rc = sg_request_status();
if (rc != 0) {
printf("problem requesting status: %s\n", sg_get_error());
return -1;
}
while(1) {
int retval;
fd_set tmpfds = rfds;
retval = select(nfds, &tmpfds, NULL, NULL, NULL);
if (retval > 0) {
rc = process_sg_msg();
if (rc < 0) {
printf("problem processing incoming msg: %s\n", sg_get_error());
}
} else if (retval == -1)
perror("select()");
}
return 0;
}

View File

@ -1,175 +0,0 @@
/*
* Copyright (c) 2013-2016, Wind River Systems, Inc.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3) Neither the name of Wind River Systems nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
build: gcc -I../ -o guest_app guest_app.c -ljson-c
*/
#include <stddef.h>
#include <errno.h>
#include <error.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/select.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <json-c/json.h>
#include "host_guest_msg_type.h"
struct json_object *create_new_jobj_data()
{
struct json_object *jobj_data = json_object_new_object();
if (jobj_data == NULL) {
printf("failed to allocate json object for data\n");
return NULL;
}
json_object_object_add(jobj_data, VERSION, json_object_new_int(CUR_VERSION));
json_object_object_add(jobj_data, "resource", json_object_new_string("cpu"));
json_object_object_add(jobj_data, "direction", json_object_new_string("down"));
return jobj_data;
}
// create app to daemon msg
const char *create_outmsg(int msg_count)
{
struct json_object *jobj_msg = json_object_new_object();
if (jobj_msg == NULL) {
printf("failed to allocate json object for msg\n");
return NULL;
}
json_object_object_add(jobj_msg, VERSION, json_object_new_int(CUR_VERSION));
json_object_object_add(jobj_msg, DEST_ADDR, json_object_new_string("h_scale_agent"));
json_object_object_add(jobj_msg, "msg_count", json_object_new_int(msg_count));
struct json_object *jobj_data = create_new_jobj_data();
if (jobj_data == NULL) {
json_object_put(jobj_msg);
return NULL;
}
json_object_object_add(jobj_msg, DATA, create_new_jobj_data());
const char *msg = json_object_to_json_string_ext(jobj_msg, JSON_C_TO_STRING_PLAIN);
return msg;
}
// create daemon to app msg
const char *create_inmsg()
{
struct json_object *jobj_msg = json_object_new_object();
if (jobj_msg == NULL) {
printf("failed to allocate json object for msg\n");
return NULL;
}
json_object_object_add(jobj_msg, VERSION, json_object_new_int(CUR_VERSION));
json_object_object_add(jobj_msg, SOURCE_ADDR, json_object_new_string("h_scale_agent"));
struct json_object *jobj_data = create_new_jobj_data();
if (jobj_data == NULL) {
json_object_put(jobj_msg);
return NULL;
}
json_object_object_add(jobj_msg, DATA, create_new_jobj_data());
const char *msg = json_object_to_json_string_ext(jobj_msg, JSON_C_TO_STRING_PLAIN);
return msg;
}
int main()
{
char buf[4096];
int len;
struct sockaddr_un cliaddr, srvaddr;
int rc;
// set up socket for talking to host agent
int fd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (fd == -1) {
perror("socket");
exit(-1);
}
memset(&cliaddr, 0, sizeof(struct sockaddr_un));
cliaddr.sun_family = AF_UNIX;
cliaddr.sun_path[0] = '\0';
strncpy(cliaddr.sun_path+1, "g_scale_agent", sizeof(cliaddr.sun_path) - 2);
if (bind(fd, (struct sockaddr *) &cliaddr, sizeof(struct sockaddr_un)) == -1) {
perror("bind");
exit(-1);
}
/* Construct address of server */
memset(&srvaddr, 0, sizeof(struct sockaddr_un));
srvaddr.sun_family = AF_UNIX;
srvaddr.sun_path[0] = '\0';
strncpy(srvaddr.sun_path+1, AGENT_ADDR, sizeof(srvaddr.sun_path) - 2);
const char* inmsg = create_inmsg();
const char* outmsg = create_outmsg(1);
len = strlen(outmsg);
rc = sendto(fd, outmsg, len, 0, (struct sockaddr *) &srvaddr,
sizeof(struct sockaddr_un));
if (rc != len) {
perror("sendto");
exit(-1);
}
outmsg = create_outmsg(2);
len = strlen(outmsg);
rc = sendto(fd, outmsg, len, 0, (struct sockaddr *) &srvaddr,
sizeof(struct sockaddr_un));
if (rc != len) {
perror("sendto");
exit(-1);
}
while (1) {
len = recv(fd, buf, sizeof(buf), 0);
if (len == -1) {
perror("recvfrom");
exit(-1);
}
printf("Msg from host: %s\n", buf);
fflush(0);
}
}

View File

@ -1,187 +0,0 @@
/*
* Copyright (c) 2013-2016, Wind River Systems, Inc.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3) Neither the name of Wind River Systems nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
build: gcc -I../ -o host_app host_app.c -ljson-c
*/
#include <stddef.h>
#include <errno.h>
#include <error.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/select.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <json-c/json.h>
#include "host_guest_msg_type.h"
struct json_object *create_new_jobj_data()
{
struct json_object *jobj_data = json_object_new_object();
if (jobj_data == NULL) {
printf("failed to allocate json object for data\n");
return NULL;
}
json_object_object_add(jobj_data, VERSION, json_object_new_int(CUR_VERSION));
json_object_object_add(jobj_data, "resource", json_object_new_string("cpu"));
json_object_object_add(jobj_data, "direction", json_object_new_string("down"));
return jobj_data;
}
// create app to daemon msg
const char *create_outmsg(int msg_count, const char *dest_instance)
{
struct json_object *jobj_msg = json_object_new_object();
if (jobj_msg == NULL) {
printf("failed to allocate json object for msg\n");
return NULL;
}
json_object_object_add(jobj_msg, VERSION, json_object_new_int(CUR_VERSION));
json_object_object_add(jobj_msg, DEST_ADDR, json_object_new_string("g_scale_agent"));
json_object_object_add(jobj_msg, DEST_INSTANCE, json_object_new_string(dest_instance));
json_object_object_add(jobj_msg, "msg_count", json_object_new_int(msg_count));
struct json_object *jobj_data = create_new_jobj_data();
if (jobj_data == NULL) {
json_object_put(jobj_msg);
return NULL;
}
json_object_object_add(jobj_msg, DATA, create_new_jobj_data());
const char *msg = json_object_to_json_string_ext(jobj_msg, JSON_C_TO_STRING_PLAIN);
return msg;
}
// create daemon to app msg
const char *create_inmsg()
{
struct json_object *jobj_msg = json_object_new_object();
if (jobj_msg == NULL) {
printf("failed to allocate json object for msg\n");
return NULL;
}
json_object_object_add(jobj_msg, VERSION, json_object_new_int(CUR_VERSION));
json_object_object_add(jobj_msg, SOURCE_ADDR, json_object_new_string("h_scale_agent"));
struct json_object *jobj_data = create_new_jobj_data();
if (jobj_data == NULL) {
json_object_put(jobj_msg);
return NULL;
}
json_object_object_add(jobj_msg, DATA, create_new_jobj_data());
const char *msg = json_object_to_json_string_ext(jobj_msg, JSON_C_TO_STRING_PLAIN);
return msg;
}
//argv[1] should be the instance name
int main(int argc, char **argv)
{
char buf[4096];
int len;
struct sockaddr_un cliaddr, srvaddr;
int rc;
if (argc != 2) {
printf("call with instance name as arg\n");
exit(1);
}
// set up socket for talking to host agent
int fd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (fd == -1) {
perror("socket");
exit(-1);
}
memset(&cliaddr, 0, sizeof(struct sockaddr_un));
cliaddr.sun_family = AF_UNIX;
cliaddr.sun_path[0] = '\0';
strncpy(cliaddr.sun_path+1, "h_scale_agent", sizeof(cliaddr.sun_path) - 2);
if (bind(fd, (struct sockaddr *) &cliaddr, sizeof(struct sockaddr_un)) == -1) {
perror("bind");
exit(-1);
}
/* Construct address of server */
memset(&srvaddr, 0, sizeof(struct sockaddr_un));
srvaddr.sun_family = AF_UNIX;
srvaddr.sun_path[0] = '\0';
strncpy(srvaddr.sun_path+1, AGENT_ADDR, sizeof(srvaddr.sun_path) - 2);
const char* inmsg = create_inmsg();
// pass argv[1] as dest_instance
const char* outmsg = create_outmsg(1, argv[1]);
len = strlen(outmsg);
rc = sendto(fd, outmsg, len, 0, (struct sockaddr *) &srvaddr,
sizeof(struct sockaddr_un));
if (rc != len) {
perror("sendto");
exit(-1);
}
outmsg = create_outmsg(2, argv[1]);
len = strlen(outmsg);
rc = sendto(fd, outmsg, len, 0, (struct sockaddr *) &srvaddr,
sizeof(struct sockaddr_un));
if (rc != len) {
perror("sendto");
exit(-1);
}
while (1) {
len = recv(fd, buf, sizeof(buf), 0);
if (len == -1) {
perror("recvfrom");
exit(-1);
}
printf("Msg from instance %s\n", buf);
fflush(0);
}
}

View File

@ -1,374 +0,0 @@
/*
* Copyright (c) 2013-2016, Wind River Systems, Inc.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3) Neither the name of Wind River Systems nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
This file is used to test functions in file host_guest_msg.c.
Functions under test are directly copied to here to simplify compile.
Once tested and refactored, the functions can be copied back to their
original location with appropriate debug traces.
build: gcc -I. -o test_host_guest_msg test_host_guest_msg.c -ljson-c
usage: binary can be executed directly on a linux desktop.
./test_host_guest_msg - run without parameters to check TCs PASS or FAIL
./test_host_guest_msg 1 - show error logs
./test_host_guest_msg 2 - show error and debug logs
*/
#include <stddef.h>
#include <errno.h>
#include <error.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/select.h>
#include <sys/un.h>
#include <json-c/json.h>
//number of guest
#define NUM_GUEST 3
//number of reads
#define NUM_READS 3
int debug = 0;
#define PRINT_ERR(format, ...) if(debug >= 1) printf(format, ##__VA_ARGS__)
#define PRINT_DEBUG(format, ...) if(debug >= 2) printf(format, ##__VA_ARGS__)
// One tokener for each instance connection serve as reassembly buffer
struct json_tokener* tok[NUM_GUEST];
void process_msg(json_object *jobj_msg, int fd);
//----------------------------------------------------------
// Functions Under Test
//----------------------------------------------------------
void parser(void *buf, ssize_t len, int fd, json_tokener* tok, int newline_found)
{
PRINT_DEBUG("parser: len=%lu, buf=%s\n", len, (char *)buf);
json_object *jobj = json_tokener_parse_ex(tok, buf, len);
enum json_tokener_error jerr = json_tokener_get_error(tok);
if (jerr == json_tokener_success) {
process_msg(jobj, fd);
json_object_put(jobj);
return;
}
else if (jerr == json_tokener_continue) {
// partial JSON is parsed , continue to read from socket
PRINT_DEBUG("partial message parsed, continue read socket\n");
PRINT_DEBUG("processed so far buf=%s\n", (char *)buf);
// if newline was found in the middle of the buffer, the message should
// be completed at this point. Throw out incomplete message by resetting
// tokener.
if (newline_found) {
PRINT_DEBUG("newline_found. throw out the partial message\n");
json_tokener_reset(tok);
}
}
else
{
PRINT_ERR("JSON Parsing Error: %s\n", json_tokener_error_desc(jerr));
json_tokener_reset(tok);
}
}
//----------------------------------------------------------
// Functions Under Test
//----------------------------------------------------------
void handle_virtio_serial_msg(void *buf, ssize_t len, int fd, json_tokener* tok)
{
void *origbuf = buf;
void *newline;
ssize_t len_head;
next:
if (len == 0)
return;
PRINT_DEBUG("analyzing buffer at offset %lu, len %zd\n", buf-origbuf, len);
// search for newline as delimiter
newline = memchr(buf, '\n', len);
if (newline) {
PRINT_DEBUG("found newline start at offset %lu\n", newline - origbuf);
// split buffer to head and tail at the location of newline.
// feed the head to the parser and recursively process the tail.
len_head = newline-buf;
// parse head
if (len_head > 0)
parser(buf, len_head, fd, tok, 1);
// start of the tail: skip newline
buf += len_head+1;
// length of the tail: deduct 1 for the newline character
len -= len_head+1;
// continue to process the tail.
goto next;
}
else {
parser(buf, len, fd, tok, 0);
}
}
// buffer to simulate socket to read, one socket per guest
void *socket[NUM_GUEST][NUM_READS];
// resulting parsed socket
char socket_processed[NUM_GUEST][NUM_READS][500];
// expected result
char *socket_expected[NUM_GUEST][NUM_READS];
// track current buffer being processed for particular guest
int current_processed[NUM_GUEST];
void free_tok()
{
int fd;
for (fd=0; fd<NUM_GUEST; fd++) {
if (tok[fd])
free(tok[fd]);
tok[fd] = NULL;
}
}
// populate socket with contents
void init_socket_result()
{
socket_expected[0][0] = "{\"name\":\"guest0\",\"seq\":1,\"data\":{\"secret\":101}}";
socket_expected[0][1] = "{\"name\":\"guest0\",\"seq\":2,\"data\":{\"secret\":102}}";
socket_expected[0][2] = "{\"name\":\"guest0\",\"seq\":3,\"data\":{\"secret\":103}}";
socket_expected[1][0] = "{\"name\":\"guest1\",\"seq\":1,\"data\":{\"secret\":201}}";
socket_expected[1][1] = "{\"name\":\"guest1\",\"seq\":2,\"data\":{\"secret\":202}}";
socket_expected[1][2] = "{\"name\":\"guest1\",\"seq\":3,\"data\":{\"secret\":203}}";
socket_expected[2][0] = "{\"name\":\"guest2\",\"seq\":1,\"data\":{\"secret\":301}}";
socket_expected[2][1] = "{\"name\":\"guest2\",\"seq\":2,\"data\":{\"secret\":302}}";
socket_expected[2][2] = "{\"name\":\"guest2\",\"seq\":3,\"data\":{\"secret\":303}}";
}
void setup_test()
{
int fd;
for (fd=0; fd<NUM_GUEST; fd++) {
tok[fd] = json_tokener_new();
current_processed[fd] = 0;
}
init_socket_result();
}
void reset_results()
{
int fd, read;
for(fd=0;fd<NUM_GUEST;fd++) {
for (read = 0; read <NUM_READS; read++) {
strcpy(socket_processed[fd][read], "\0");
}
current_processed[fd] = 0;
}
}
// populate socket with contents
void init_socket_tc1()
{
reset_results();
socket[0][0] = "\n{\"name\":\"guest0\",\"seq\":1,\"data\":{\"secret\":101}}\n";
socket[0][1] = "\n{\"name\":\"guest0\",\"seq\":2,\"data\":{\"secret\":102}}\n";
socket[0][2] = "\n{\"name\":\"guest0\",\"seq\":3,\"data\":{\"secret\":103}}\n";
socket[1][0] = "\n{\"name\":\"guest1\",\"seq\":1,\"data\":{\"secret\":201}}\n";
socket[1][1] = "\n{\"name\":\"guest1\",\"seq\":2,\"data\":{\"secret\":202}}\n";
socket[1][2] = "\n{\"name\":\"guest1\",\"seq\":3,\"data\":{\"secret\":203}}\n";
socket[2][0] = "\n{\"name\":\"guest2\",\"seq\":1,\"data\":{\"secret\":301}}\n";
socket[2][1] = "\n{\"name\":\"guest2\",\"seq\":2,\"data\":{\"secret\":302}}\n";
socket[2][2] = "\n{\"name\":\"guest2\",\"seq\":3,\"data\":{\"secret\":303}}\n";
}
void init_socket_tc2()
{
reset_results();
socket[0][0] = "\n{\"name\":\n{\"name\":\"guest0\",\"seq\":1,\"data\":{\"secret\":101}";
socket[0][1] = "}\n\n{\"name\":\"guest0\",\"seq\":2,\"data\":{\"secret\":102}}\n";
socket[0][2] = "\n{\"name\":\"guest0\",\"seq\":3,\"data\":{\"secret\":103}}\n";
socket[1][0] = "\n";
socket[1][1] = "{\"name\":\"guest1\",\"seq\":1,\"data\":{\"secret\":201}}";
socket[1][2] = "\n\n{\"name\":\"guest1\",\"seq\":2,\"data\":{\"secret\":202}}\n\n{\"name\":\"guest1\",\"seq\":3,\"data\":{\"secret\":203}}\n";
socket[2][0] = "\n{\"name\":\"guest2\",\"seq\":1,\"data\":{\"secret\":301}";
socket[2][1] = "}\n\n{\"name\":\"guest2\",\"seq\":2,\"data\":{\"secret\":302";
socket[2][2] = "}}\n\n{\"name\":\"guest2\",\"seq\":3,\"data\":{\"secret\":303}}\n";
}
// insert garbage characters
void init_socket_tc3()
{
reset_results();
socket[0][0] = "\n{\"name\":\"guest0\",\"s";
socket[0][1] = "eq\":1,\"data\":{\"secret\":101}}\\nJHgB\7b4\\sx34xbb\n{\"name\":\"guest0\",\"seq\":2,\"data\":{\"secret\":102}}\n7b4x34";
socket[0][2] = "\n{\"name\":\"guest0\",\"seq\":3,\"data\":{\"secret\":103}}\n";
socket[1][0] = "\n{\"name\":\"guest1\",\"seq\":1,\"data\":{\"secret\":201}}\n7x4\xa}}{{\n{\"name\":";
socket[1][1] = "\"guest1\",\"seq\":2,\"data\":{\"secret\"";
socket[1][2] = ":202}}}} \n\n{\"name\":\"guest1\",\"seq\":3,\"data\":{\"secret\":203}}\n";
socket[2][0] = "\n{\"name\":\"guest2\",\"seq\":1,\"data\":{\"secret\":301}";
socket[2][1] = "}\n\n*&*&*&\n{\"name\":\"guest2\",\"seq\":2,\"data\":{\"secret\":302";
socket[2][2] = "}}\n\n{\"name\":\"guest2\",\"seq\":3,\"data\":{\"secret\":303}}%%$%#$%#$%\n";
}
void init_socket_tc4()
{
reset_results();
socket[0][0] = "\n{\"name\":\"guest0\",\"seq\":1,\"data\":{\"secret\":101}}\n\n{\"name\":\"guest0\",\"seq\":2,\"data\":{\"secret\":102}}\n*^*&%^*{{%$\n{\"name\":\"guest0\",\"seq\":3,\"data\":{\"secret\":103}}\n";
socket[0][1] = "\n";
socket[0][2] = "\n{\"name\":\n";
socket[1][0] = "\n{\"name\":\"guest1\",\"seq\":1,\"data\":{\"secret\":201}}\n\n{\"name\":\"guest1\",\"seq\":2,\"data\":";
socket[1][1] = "{\"secret\":202}}\n\n{\"name\":\"guest1\",\"seq\":";
socket[1][2] = "3,\"data\":{\"secret\":203}}\n";
socket[2][0] = "\n{\"name\":\"guest2\",\"seq\":1,\"data\"";
socket[2][1] = ":{\"secret\":301}}\n\n{\"name\":\"guest2\",\"seq\":2,\"data\":{\"secret\":302}}\n\n{\"name\":\"guest2\",\"seq\":3,\"data\":{\"secret\"";
socket[2][2] = ":303}}\n";
}
void check_results()
{
int fd, read;
for(fd=0;fd<NUM_GUEST;fd++) {
for (read = 0; read <NUM_READS; read++) {
if (strcmp(socket_processed[fd][read], socket_expected[fd][read])!= 0 ) {
printf("FAIL\n guest %d read %d not correct:\n expect=%s\n actual=%s\n", fd, read, socket_expected[fd][read], socket_processed[fd][read]);
return;
}
}
}
printf("PASS\n");
}
void process_msg(json_object *jobj_msg, int fd)
{
const char *msg = json_object_to_json_string_ext(jobj_msg, JSON_C_TO_STRING_PLAIN);
if (msg[0]!='{'){
PRINT_DEBUG("*********throw out processed msg*********** %s\n", msg);
return;
}
PRINT_DEBUG("successfully processed guest=%d, read=%d, msg=%s\n", fd, current_processed[fd], msg);
strcpy (socket_processed[fd][current_processed[fd]], msg);
current_processed[fd]++;
}
void scan_guest_fd(int fd, int read)
{
char *buf;
// read from socket for guest fd
buf = socket[fd][read];
PRINT_DEBUG("handling guest=%d, read=%d, buf=%s\n", fd, read, buf);
handle_virtio_serial_msg(buf, strlen(buf), fd, tok[fd]);
}
int main(int argc, char **argv)
{
int read;
int fd;
if (argc > 1)
debug = atoi(argv[1]);
setup_test();
printf("\n===== TC1 one valid message per read: ");
init_socket_tc1();
for (read = 0; read <NUM_READS; read++) {
for(fd=0;fd<NUM_GUEST;fd++) {
scan_guest_fd(fd, read);
}
}
check_results();
printf("\n===== TC2 partial messages: ");
init_socket_tc2();
for (read = 0; read <NUM_READS; read++) {
for(fd=0;fd<NUM_GUEST;fd++) {
scan_guest_fd(fd, read);
}
}
check_results();
printf("\n===== TC3 garbage in between messages: ");
init_socket_tc3();
for (read = 0; read <NUM_READS; read++) {
for(fd=0;fd<NUM_GUEST;fd++) {
scan_guest_fd(fd, read);
}
}
check_results();
printf("\n===== TC4 multiple messages: ");
init_socket_tc4();
for (read = 0; read <NUM_READS; read++) {
for(fd=0;fd<NUM_GUEST;fd++) {
scan_guest_fd(fd, read);
}
}
check_results();
free_tok();
return 0;
}